Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 50 ยท Authentication and security

API keys and security practices

Protect a FastAPI service with API key headers, rate limiting, strict CORS, request size limits, secure secrets and security headers, with live examples.

User logins and OAuth2 tokens suit apps with people in them. Plenty of APIs are called by programs instead: a billing script, a partner's server, a monitoring tool. For those, the usual credential is an API key: a long random string sent in a header. Keys are simple, but a key alone does not make an API safe. You also need limits on how often and how much a caller can send, a careful CORS setup, secrets that never reach your repository, and a few response headers that tell browsers to behave.

This lesson walks through each of these with code you can run, and ends with a short checklist based on the common API security risks.

API keys in a header

FastAPI ships APIKeyHeader, a security scheme that reads one named header (conventionally X-API-Key) and documents it in the OpenAPI file. Setting auto_error=False lets you give the response yourself.

Three habits make key handling much safer:

  1. Generate keys with secrets, never by hand: secrets.token_urlsafe(32) gives 256 bits of randomness.
  2. Store only a hash of each key, like a password (see Password hashing and user accounts). Keys are long and random, so a fast hash such as SHA-256 is enough; the slow password hashes exist to protect guessable secrets.
  3. Compare in constant time with secrets.compare_digest. A plain == can return faster when the first characters differ, which in theory leaks information.

Show the full key to its owner exactly once, when it is created.

Python An API key dependency with hashed storage

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The server never stored the key itself, only its digest, yet it can recognize the key when it comes back. Revoking is a flag flip. Because keys are credentials, send them only over HTTPS, and prefer a header over the query string: URLs end up in logs, browser history and proxy caches.

An API key identifies a program. It must never ship inside a browser or mobile app, because anyone can read it there. If code running on a user's device needs access, give the user their own short-lived token instead.

Rate limiting

Even honest clients have bugs, and dishonest ones have scripts. A rate limit caps how many requests one caller may make in a time window, and answers 429 Too Many Requests (with a Retry-After header) beyond that. It protects your database, your bill and your login endpoint from password guessing.

The simplest design is a fixed window: count requests per key per minute. The version below keeps counts in a dictionary, which is fine for explaining the idea but wrong for production, since every worker process would have its own counters and they vanish on restart. Real services keep the counters in Redis, or let the reverse proxy or API gateway enforce the limit before the request even reaches Python.

To make the demo deterministic, the clock is a variable we move by hand instead of time.time().

Python A fixed-window rate limiter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Requests 1 to 3 pass and show a shrinking X-RateLimit-Remaining; requests 4 and 5 are refused with a Retry-After of 20 seconds (the time left in the window). A different caller has its own counter, and when the window rolls over, the first caller is welcome again. Fixed windows have a known weakness: a caller can send a full burst at the end of one window and another at the start of the next. Sliding windows and token buckets smooth that out, at the cost of a little more bookkeeping.

Limit sizes, not just counts

Every input needs an upper bound, or a single request can use all your memory. Pydantic constraints (Field(max_length=...), Query(le=100) for page sizes) handle individual fields; see Field constraints and validators. A middleware can reject oversized bodies early, using the Content-Length header. Your web server (nginx's client_max_body_size, for instance) should enforce the same limit, because a client may lie about or omit the header.

Security headers and CORS

Browsers obey instructions that come in response headers. A tiny middleware can add the useful ones to every response:

  • X-Content-Type-Options: nosniff: do not guess content types.
  • Strict-Transport-Security: remember to use HTTPS for this host (send it only when you really serve HTTPS).
  • Cache-Control: no-store for responses with private data.
  • Content-Security-Policy and X-Frame-Options matter mostly when you serve HTML.

CORS (cross-origin resource sharing) is the browser rule that blocks a page on https://app.example from reading responses of https://api.example unless the API opts in. It is a browser protection: curl and your backend scripts ignore it, so it is never a replacement for authentication. Middleware and CORS explains the settings; the pitfalls to remember here:

  • allow_origins=["*"] lets every website read your public responses. Fine for truly public data, wrong for anything private.
  • Wildcard origins with allow_credentials=True are rejected by browsers, and you should list exact origins when cookies are involved.
  • Reflecting whatever Origin arrives back into the header is the same as a wildcard.
Python Size limit, security headers and strict CORS

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice what the last two lines prove: the request from the unknown origin was still processed (the server does not block it), but the response lacks Access-Control-Allow-Origin, so a browser would refuse to hand the answer to that page. That is why CORS cannot guard an API on its own.

Secrets handling

Passwords, API keys, signing keys and database URLs are secrets. Rules that prevent most leaks:

  • Keep them out of source control. Read them from environment variables, as in Settings and configuration, or from your platform's secret store.
  • Use a different value per environment. A leaked development key must be worthless in production.
  • Never log secrets or put them in error messages, URLs or exception text. Log a key's prefix or id instead.
  • Make rotation easy: allow two valid keys during a changeover, then revoke the old one.
  • Commit a .env.example with fake values, and add the real .env to .gitignore.

An API risk checklist

The OWASP project keeps a list of the most common API security failures. In plain words, with the FastAPI answer next to each:

Risk Typical FastAPI answer
Object-level authorization missing (BOLA) Ownership dependency, see Roles, scopes and permissions
Broken authentication Hashed passwords, expiring tokens, rate-limited login
Excessive data in responses response_model that omits secret fields, see Response models
Unrestricted resource use Page size limits, body size limits, rate limiting, timeouts
Function-level authorization missing Guards on routers, deny by default
Security misconfiguration Strict CORS, debug off, docs disabled or protected if the API is private
Mass assignment Separate input schemas that list only writable fields
Unsafe consumption of other APIs Validate data from third parties like any other input

Two more habits: keep dependencies updated (pip list --outdated in CI), and turn off /docs and /openapi.json in production with FastAPI(docs_url=None, redoc_url=None, openapi_url=None) if the API is internal.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why compare API keys with secrets.compare_digest instead of ==?

    Constant-time comparison avoids leaking, through timing, how much of a guess was correct.
  2. 2. A client exceeds the rate limit. Which response is the right one?

    429 is the standard status for rate limiting, and Retry-After tells the client when it may try again.
  3. 3. Does a strict CORS policy stop a script using curl from calling your API?

    CORS tells browsers whether a web page may read a response. Other clients ignore it, so authentication is still required.
  4. 4. How should the server store API keys?

    A hash lets the server verify a key without being able to reveal it, so a leaked database does not leak working keys.

Summary

  • An API key is a long random header value for programs. Generate it with secrets, store only its hash, compare in constant time and revoke by flag.
  • Rate limits answer 429 with Retry-After; per-process dictionaries are only a teaching tool, so use Redis or the proxy in production.
  • Bound every input: field constraints, page sizes and a body size limit enforced both in the app and at the web server.
  • Security headers and a strict CORS list instruct browsers, but CORS is not authentication.
  • Keep secrets in the environment, vary them per environment, never log them and plan for rotation.

Next: SQLAlchemy with FastAPI connects your endpoints to a real database.