Skip to content

Chapter 6.5: API Security Basics

Study Time: 45 minutes


1. API Security: Multi-Level Station Defense

Imagine your space station (API) is in a hostile sector of space. A single force field (authentication) is not enough. You need a comprehensive defense system:

  • Shields (HTTPS): Encryption of all traffic.
  • Anomaly Sensors (Rate Limiting): Protection against too frequent requests.
  • Internal Bulkheads (Authorization): Separation of access rights.
  • Cargo Inspection (Validation): Do not trust any incoming data.
  • Secret Safe (Environment Variables): Secure storage of keys.

Let's configure each of these levels.


2. Shields: Always Use HTTPS

What is it? HTTPS (HyperText Transfer Protocol Secure) is a version of the HTTP protocol that encrypts all data between the client and the server. Without it, anyone who "listens" to the network (for example, on public Wi-Fi) can intercept logins, passwords, and tokens.

How to implement it?

  • On production — mandatory. When deploying your API to a real server (Heroku, DigitalOcean, etc.), configure the web server (Nginx, Apache) to work with an SSL certificate. Services like Let's Encrypt provide free certificates.
  • In local development, this is less critical, but tools like Laravel Herd or mkcert make it easy to set up local HTTPS.

💡 Rule #1 in API security: No HTTPS — no security.


3. Anomaly Sensors: Rate Limiting

What is it? Protection against Brute-force attacks (when an attacker tries to guess a password by sending thousands of requests per second) and against DoS attacks (when the server is "flooded" with requests to make it stop responding). Rate Limiting limits the number of requests that a single user (or IP address) can make in a certain period of time.

How to implement it?

  • In Laravel: The middleware for limiting is already built in! Open app/Http/Kernel.php and look at the middlewareGroups['api'] key. It already has 'throttle:api'. The settings for this limitation are in app/Providers/RouteServiceProvider.php in the configureRateLimiting() method.

    // app/Providers/RouteServiceProvider.php
    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });
    }
    
    This means: 60 requests per minute per user (if authorized) or per IP address.

  • In FastAPI: A third-party package is used, for example, slowapi.

  • Installation: pip install slowapi

  • Integration into main.py:
    # main.py
    from slowapi import Limiter, _rate_limit_exceeded_handler
    from slowapi.util import get_remote_address
    from slowapi.errors import RateLimitExceeded
    
    limiter = Limiter(key_func=get_remote_address)
    app = FastAPI(...)
    
    # Connect the error handler and the limiter itself
    app.state.limiter = limiter
    app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
    
    # Apply to a specific endpoint
    @router.get("/planets")
    @limiter.limit("5/minute") # 5 requests per minute
    def get_planets(request: Request):
        # ...
    

4. Internal Bulkheads: Authorization (not to be confused with authentication!)

What is it?

  • Authentication answers the question "Who are you?".
  • Authorization answers the question "What are you allowed to do?".

For example, a regular user can view planets, but only a user with the "administrator" role can delete them.

How to implement it?

  • In Laravel: Policies or Gates are used.

  • Create a policy: php artisan make:policy PlanetPolicy --model=Planet

  • Describe the rules in app/Policies/PlanetPolicy.php:
    class PlanetPolicy
    {
        // Allow deletion only for users with the 'admin' role
        public function delete(User $user, Planet $planet): bool
        {
            return $user->role === 'admin';
        }
    }
    
  • Apply the policy in the PlanetController.php controller:

    public function destroy(Planet $planet)
    {
        // Check if the current user has the right to delete
        $this->authorize('delete', $planet);
    
        $planet->delete();
        return response()->json(null, 204);
    }
    

  • In FastAPI: Authorization logic is usually written manually inside the endpoints, using user information obtained from the token.

# (assuming the token has a 'roles' field)
def get_current_active_user(token: str = Depends(oauth2_scheme)):
    # ... decode the token and get the user with roles from the DB
    # user = get_user_from_db(username)
    return user # return the user object

@router.delete("/planets/{planet_id}")
def delete_planet(
    planet_id: int,
    current_user: User = Depends(get_current_active_user)
):
    if "admin" not in current_user.roles:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Insufficient permissions to perform this operation",
        )
    # ... deletion logic ...

5. Cargo Inspection and the Secret Safe: Validation and Environment Variables

We have already implemented these two points, but it is important to emphasize their role in security.

  • Never trust incoming data (Validation):

  • We used $request->validate() in Laravel and Pydantic models in FastAPI. This protects us from SQL injections (when using Eloquent/SQLAlchemy) and incorrect data that can break the application. Always validate everything that comes from the outside!

  • Store secrets in .env (Environment Variables):

  • Database keys, secret keys for JWT (SECRET_KEY), third-party service keys — all of this should never get into the version control system (Git). This is what .env files, which are added to .gitignore, are for.


Reinforcement Quiz

1. To protect against data interception on public networks, you should use:

2. Rate Limiting primarily protects against:

3. The question "What is this user allowed to do?" is solved by:

4. Secret API keys and database passwords should be stored:


🚀 Course Completion Congratulations, Commander! You have successfully completed all missions.

You have gone from a beginner who had only heard about APIs to an engineer capable of independently designing, developing, documenting, securing, and testing a full-fledged web service on two of the most popular technologies in their ecosystems.

You have mastered the universal language of REST, learned Laravel and FastAPI, and built a "Mission Control Center" for them in pure JavaScript.

This is a huge achievement. The world of API development is now open to you. Continue to explore, learn, and build amazing things.

End of communication. 🚀

☄ Support the Mission

Creating this tutorial is a long and complex flight that requires a lot of time and energy. If the material was useful to you, you can help refuel our expedition's fuel tanks. Each support is another orbit towards new useful materials.

Buy Me a Coffee at ko-fi.com