Lesson 54 of 59Production
API Security
The API risks attackers actually exploit, and the FastAPI habits that stop them, from object-level checks to headers and dependency audits.
Most API breaches are not clever. An attacker changes /orders/812 to /orders/813 and reads a stranger's order. A signup endpoint accepts "is_admin": true because the model passed the whole body to the database. A search endpoint with no page size limit returns two million rows and takes the service down. The authentication lesson showed how to know who is calling. This lesson is about everything after that: what they may touch, what you send back, what you accept, and the configuration around your app.
The OWASP API Security Top 10, in plain words
OWASP is a non-profit that publishes lists of the most common web security risks. Its API Security Top 10 is the checklist security reviewers reach for. The ones you will meet most as a backend developer:
- Broken object level authorization (BOLA). The API checks that you are logged in, but not that the object you asked for is yours. It sits at number one for a reason.
- Broken authentication. Weak login: no rate limit on password guesses, tokens that never expire, secrets that are easy to guess.
- Broken object property level authorization. Two sides of one bug: returning fields the caller should not see (excessive data exposure), and accepting fields the caller should not set (mass assignment).
- Unrestricted resource consumption. No limits on request size, page size, upload size or request rate, so one client can exhaust your CPU, memory, database or bill.
- Broken function level authorization. A regular user can call an admin endpoint because nobody checked the role.
- Security misconfiguration. Debug mode in production, permissive CORS, missing security headers, verbose error messages.
Injection (SQL, shell commands) is a top risk in OWASP's general web list, and it applies to APIs just the same. The rest of the API list covers server-side request forgery, abuse of business flows, forgotten old API versions and trusting third-party APIs too much. Read the full list once; it is short.
Match each bug to its OWASP category.
Object and function level authorization
The fix for BOLA is to make ownership part of every query, so a missing check fails closed. Do not fetch by id and compare afterwards in some routes and forget in others. Put the rule in one place:
from sqlalchemy import select
from sqlalchemy.orm import Session
from app.models import Order
def get_order_for_user(db: Session, order_id: int, user_id: int) -> Order | None:
stmt = select(Order).where(Order.id == order_id, Order.user_id == user_id)
return db.scalars(stmt).first()The route raises 404 when it gets None, so an attacker cannot even learn that order 813 exists. Random UUIDs instead of sequential ids make guessing harder, but they are not authorization: ids leak through URLs, logs and shared links. Always check.
For function level authorization, write the role check once as a dependency and attach it to the whole router, so a new admin route cannot forget it:
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, status
from app.api.auth import CurrentUser
from app.models import User
def require_admin(user: CurrentUser) -> User:
if user.role != "admin":
raise HTTPException(status.HTTP_403_FORBIDDEN, "Admins only")
return user
AdminUser = Annotated[User, Depends(require_admin)]
admin_router = APIRouter(prefix="/admin", dependencies=[Depends(require_admin)])Test both rules explicitly: one test per endpoint where user A asks for user B's object and expects 404, and one where a regular user calls an admin route and expects 403. These are the tests that catch real breaches.
GET /orders/{order_id} requires a valid JWT and loads the order with db.get(Order, order_id). What is the vulnerability, and the best fix?Validate input, shape output
Pydantic is your first line of defence, but only if your models are strict. Give every field limits, forbid unknown fields, and use separate models for input and output.
from typing import Annotated
from pydantic import BaseModel, ConfigDict, Field
Name = Annotated[str, Field(min_length=1, max_length=100)]
class UserUpdate(BaseModel):
model_config = ConfigDict(extra="forbid") # unknown fields are a 422, not ignored
display_name: Name | None = None
bio: Annotated[str, Field(max_length=2000)] | None = None
tags: Annotated[list[Name], Field(max_length=20)] = []
class UserPublic(BaseModel):
id: int
display_name: str
bio: str | NoneUserUpdate has no role or is_admin field, so mass assignment is impossible: there is nothing to assign to. When you apply it, use update.model_dump(exclude_unset=True) and set only those keys. On the way out, declare -> UserPublic (or response_model=UserPublic) and FastAPI filters the response down to those fields, even if you return the full ORM object with its password hash. Never return ORM objects or dict(row) without a response model.
Length limits matter too. A 50 MB string in a bio field is a resource-consumption attack. Cap page sizes in your pagination dependency (le=100), cap upload sizes, and set a maximum request body size at your proxy or load balancer.
Rate limits are the other half of resource control. Limit requests per client (by user id when authenticated, by IP otherwise) and answer 429 Too Many Requests with a Retry-After header when a client goes over. Be strictest on expensive or sensitive endpoints: login, password reset, signup and anything that sends email or SMS. A login endpoint without a limit is an open invitation to try millions of passwords. Limits usually live at the API gateway or load balancer, or in the app with a counter in Redis so every worker shares the same count; the middleware lesson's rate limiter exercise shows the core idea. Pair limits with timeouts on every outbound call, so one slow dependency cannot tie up all your workers.
Injection
The databases lesson showed why you never build SQL with f-strings and how parameters fix it, and Python Security Pitfalls in the Python course covers shell and pickle injection. Two cases still catch experienced developers.
First, identifiers cannot be parameters. A placeholder can stand in for a value, but not for a column name, so a ?sort= option tempts people back into f-strings. Use an allowlist:
Press Run (⌘ Enter) to see what happens.The user's text never reaches the SQL. It is only a key used to look up a string you wrote. In FastAPI, sort: Literal["name", "price", "newest"] gets Pydantic to enforce the same allowlist and documents it in /docs.
Second, shell commands. If you call another program, pass a list of arguments, subprocess.run(["convert", path, "out.png"]), and never shell=True with user input in the string. With a list, a filename like x; rm -rf / is just a strange filename.
Using list_products from above, what does this print?
print(list_products("name", 50))CORS, secrets and dependencies
CORS done right means listing exact origins from settings, never ["*"] together with credentials, and never reflecting back whatever Origin the request sent (some hand-written middleware does this, and it disables the protection entirely). Remember that CORS only constrains browsers. It is not authentication.
Secrets (database passwords, JWT signing keys, API keys) come from environment variables or your platform's secret manager, loaded through your settings class. Type them as Pydantic's SecretStr so they print as ********** if a settings object ever ends up in a log. Keep .env in .gitignore, turn on your Git host's secret scanning, and if a secret is ever committed, rotate it. Deleting the commit is not enough, because clones and forks still have it.
Dependencies are code you did not write running with your app's permissions. Commit a lockfile so you install exactly what you tested, and scan it for known vulnerabilities. pip-audit checks installed packages or a requirements file against public vulnerability databases. With uv you can export the lockfile to requirements format and audit that:
uv export --format requirements-txt --no-hashes > /tmp/requirements.txtuvx pip-audit -r /tmp/requirements.txtFlags change over time, so check the pip-audit docs for the current options. Run it in CI and turn on Dependabot or Renovate so upgrades arrive as small pull requests instead of one scary jump a year later.
HTTPS and security headers
Every production API must use HTTPS. Usually the load balancer terminates TLS and redirects plain HTTP, so your app never sees unencrypted traffic from the internet. Then add a few response headers. Most of them were designed for HTML pages, but they cost nothing and close gaps if an endpoint ever serves HTML or a file:
SECURITY_HEADERS = {
"Strict-Transport-Security": "max-age=31536000; includeSubDomains", # HTTPS only, remembered
"X-Content-Type-Options": "nosniff", # browsers trust Content-Type, no guessing
"Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
"Referrer-Policy": "no-referrer",
}
@app.middleware("http")
async def security_headers(request: Request, call_next):
response = await call_next(request)
response.headers.update(SECURITY_HEADERS)
return responseBe careful with a strict Content-Security-Policy on /docs: Swagger UI loads scripts and styles, so either exempt that path or disable the docs in production with FastAPI(docs_url=None, redoc_url=None, openapi_url=None) if your API is not public.
The edge drops plain HTTP, oversized bodies and floods before your code runs.
user = User(**payload) with the raw JSON body and saves it. What is the cleanest fix?- BOLA
- Broken object level authorization: an API returns or changes an object without checking the caller may access it.
- mass assignment
- Copying request fields straight onto a model, letting a caller set fields like
rolethey should not control. - excessive data exposure
- Returning more fields than the client needs, such as hashes or internal flags. Fixed with response models.
- allowlist
- Accepting only known-good values (fields, sort keys, origins) instead of trying to block bad ones.
- HSTS
- A header telling browsers to use HTTPS only for this domain for a set time.
- pip-audit
- A tool that checks your Python dependencies against databases of known vulnerabilities.
- defence in depth
- Several independent security layers, so one failing does not expose the system.