tezvyn:

API Keys: Simple Server-to-Server Authentication

AI-drafted, machine-checkedSource: fastapi.tiangolo.comintermediate

An API key is a simple secret token a client sends to prove its identity, often in a request header. It's ideal for machine-to-machine communication where a user login flow is unnecessary. Footgun: Never send keys in URL query parameters.

WHY IT EXISTS API key authentication exists to provide a simple, non-interactive way for a machine or service to authenticate itself to an API. Unlike complex flows like OAuth2 which often involve user consent and browser redirects, API keys are straightforward tokens designed for trusted, programmatic clients.

THE MENTAL MODEL Think of an API key as a key to a building's utility closet, not a key to a specific person's office. The key itself grants access; it doesn't matter who holds it. Any program with the key can open the door. This is different from a user's password, which is tied to their personal identity and permissions.

HOW IT WORKS A client includes its secret API key with each request it makes. The most secure and common method is to place it in a custom HTTP header, like X-API-Key: your-secret-string. Your FastAPI application then uses a security dependency, like APIKeyHeader, to extract this value. The app checks if the provided key is valid, typically by looking it up in a database or a secure configuration file. If the key is valid and active, the request is processed; otherwise, it's rejected with a 401 or 403 error.

WHEN TO USE IT Use API keys for server-to-server communication, internal microservices that need to talk to each other, or for granting third-party developers access to public, non-user-specific data (e.g., a public weather API). It excels when the client is a trusted, non-interactive program.

WHEN NOT TO USE IT Do not use API keys to directly authenticate end-users in a web or mobile app. For that, use a protocol like OAuth2 that ties access to a specific user's identity and session. Also, avoid API keys if you need granular, per-user permissions, as a basic API key often grants the same level of access to any client that possesses it.

ONE CANONICAL EXAMPLE A third-party monitoring service needs to pull health check data from your API. You generate a unique API key for this service and share it securely. The service configures its requests to your /health endpoint to include the header Authorization: ApiKey <the-key>. Your FastAPI app uses the APIKeyHeader dependency on that endpoint to ensure only requests with that valid key can access it. All other requests are rejected.

Read the original → fastapi.tiangolo.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.