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.
API key authentication in FastAPI
Start learning this pattern below
Jump into concepts and practice - no test required
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.
X-API-Key.api_key_header = APIKeyHeader(name="X-API-Key")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": "Access granted"}
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.
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."}
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.
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.
Practice
Solution
Step 1: Understand API key authentication purpose
API key authentication is used to protect APIs by requiring a secret key from clients.Step 2: Identify the correct purpose in options
Only To restrict access to the API by requiring a secret key in requests describes restricting access using a secret key, which matches the purpose.Final Answer:
To restrict access to the API by requiring a secret key in requests -> Option AQuick Check:
API key authentication = restrict access [OK]
- Confusing API key with speeding up API
- Thinking API key generates docs
- Assuming API key changes response format
Solution
Step 1: Identify the correct security class for API key in header
FastAPI providesAPIKeyHeaderto extract API keys from headers.Step 2: Compare options to find the exact import
from fastapi.security import APIKeyHeader importsAPIKeyHeaderfromfastapi.security, which is correct.Final Answer:
from fastapi.security import APIKeyHeader -> Option BQuick Check:
API key header extractor = APIKeyHeader [OK]
- Using OAuth2PasswordBearer for API keys
- Confusing Header with APIKeyHeader
- Missing import from fastapi.security
from fastapi import FastAPI, Security, HTTPException
from fastapi.security import APIKeyHeader
app = FastAPI()
api_key_header = APIKeyHeader(name='X-API-Key')
@app.get('/secure')
async def secure_endpoint(api_key: str = Security(api_key_header)):
if api_key != 'secret123':
raise HTTPException(status_code=403, detail='Invalid API Key')
return {'message': 'Access granted'}Solution
Step 1: Understand Security dependency behavior
If the required header 'X-API-Key' is missing, FastAPI returns a 422 error before entering the function.Step 2: Analyze the code's error handling
The 403 error triggers only if the key is present but incorrect. Missing header causes 422 instead.Final Answer:
422 Unprocessable Entity error -> Option DQuick Check:
Missing header = 422 error [OK]
- Assuming missing key triggers 403 error
- Expecting 200 OK without key
- Thinking server crashes with 500 error
from fastapi import FastAPI, Security, HTTPException
from fastapi.security import APIKeyHeader
app = FastAPI()
api_key_header = APIKeyHeader(name='X-API-Key')
@app.get('/data')
async def get_data(api_key: str = api_key_header):
if api_key != 'topsecret':
raise HTTPException(status_code=401, detail='Unauthorized')
return {'data': 'Here is your data'}Solution
Step 1: Check how APIKeyHeader is used in dependency
FastAPI requires Security() to wrap APIKeyHeader for dependency injection.Step 2: Identify missing Security() in parameter
The code usesapi_key: str = api_key_headerinstead ofSecurity(api_key_header).Final Answer:
Missing Security() wrapper around api_key_header in function parameter -> Option AQuick Check:
APIKeyHeader needs Security() [OK]
- Omitting Security() causes injection failure
- Using wrong header name is not an error here
- HTTP status 401 is acceptable for unauthorized
Solution
Step 1: Understand code reuse in FastAPI dependencies
FastAPI encourages reusable dependencies to share logic like API key checks.Step 2: Identify best practice for API key checks
Creating a dependency function with Security() allows clean reuse across endpoints.Final Answer:
Create a reusable dependency function that checks the API key and use Security() with it -> Option CQuick Check:
Reusable dependency = clean, DRY code [OK]
- Copy-pasting code leads to duplication
- Using global variables breaks encapsulation
- Disabling authentication is insecure
