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
This means: 60 requests per minute per user (if authorized) or per IP address.app/Http/Kernel.php
and look at themiddlewareGroups['api']
key. It already has'throttle:api'
. The settings for this limitation are inapp/Providers/RouteServiceProvider.php
in theconfigureRateLimiting()
method. -
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
: -
Apply the policy in the
PlanetController.php
controller: -
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
🚀 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.