API key authentication helps protect your app by checking if the user has a secret key. It stops strangers from using your app without permission.
0
0
API key authentication in FastAPI
Introduction
You want to let only trusted users access your API.
You need a simple way to secure your app without complex login systems.
You want to track who is using your API by giving each user a unique key.
You want to quickly block a user by disabling their API key.
You want to protect certain routes in your FastAPI app from public access.
Syntax
FastAPI
from fastapi import FastAPI, Security, HTTPException from fastapi.security.api_key import APIKeyHeader api_key_header = APIKeyHeader(name="X-API-Key") app = FastAPI() async def get_api_key(api_key: str = Security(api_key_header)): if api_key != "mysecretkey": raise HTTPException(status_code=403, detail="Could not validate API key") return api_key @app.get("/protected") async def protected_route(api_key: str = Security(get_api_key)): return {"message": "You have access!"}
Use APIKeyHeader to read the API key from request headers.
The Security function helps FastAPI check the key automatically.
Examples
This sets up FastAPI to look for the API key in the header named
X-API-Key.FastAPI
api_key_header = APIKeyHeader(name="X-API-Key")This function checks if the API key matches the secret key and blocks access if not.
FastAPI
async def get_api_key(api_key: str = Security(api_key_header)): if api_key != "mysecretkey": raise HTTPException(status_code=403, detail="Could not validate API key") return api_key
This route is protected and only accessible if the API key is valid.
FastAPI
@app.get("/protected") async def protected_route(api_key: str = Security(get_api_key)): return {"message": "Access granted"}
Sample Program
This FastAPI app has one protected route /secure-data. It requires the header X-API-Key with the value supersecret123. If the key is missing or wrong, it returns a 403 error.
FastAPI
from fastapi import FastAPI, Security, HTTPException from fastapi.security.api_key import APIKeyHeader api_key_header = APIKeyHeader(name="X-API-Key") app = FastAPI() async def get_api_key(api_key: str = Security(api_key_header)): if api_key != "supersecret123": raise HTTPException(status_code=403, detail="Could not validate API key") return api_key @app.get("/secure-data") async def secure_data(api_key: str = Security(get_api_key)): return {"data": "This is protected data."}
OutputSuccess
Important Notes
Always keep your API keys secret and do not share them publicly.
Use HTTPS to keep API keys safe during transmission.
You can store multiple valid API keys and check if the provided key is in that list.
Summary
API key authentication protects your API by requiring a secret key in requests.
FastAPI makes it easy to check API keys using APIKeyHeader and Security.
Use this method to control who can access your app and keep your data safe.