FastAPI is a powerful web framework for building APIs quickly and efficiently in Python. But once your API is public, you’ll want to protect it from abuse. One simple and effective way is using API Keys.
In this post, I’ll show you how to set up basic API Key validation in FastAPI.
🔐 Why API Keys?
API Keys let you:
- Identify the client making requests
- Limit usage (rate limiting, quota)
- Disable keys without affecting others
- Secure endpoints behind access controls
🛠️ Step 1: Define Your API Key Dependency
We'll use FastAPI's dependency injection system to require API keys on specific routes.
from fastapi import FastAPI, Depends, HTTPException, Header, status
app = FastAPI()
API_KEYS = {"123456", "abcdef", "my-secret-key"} # Normally load this from a database or environment
def verify_api_key(x_api_key: str = Header(...)):
if x_api_key not in API_KEYS:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or missing API Key"
)
@app.get("/public")
def public_endpoint():
return {"message": "This is public"}
@app.get("/protected", dependencies=[Depends(verify_api_key)])
def protected_endpoint():
return {"message": "You have access with a valid API key"}
🧪 Testing
You can test it with curl
or Postman:
curl http://localhost:8000/protected -H "x-api-key: 123456"
If the key is valid, you’ll get access. Otherwise, a 401 Unauthorized response.
📦 Optional: Use Limitly to Manage Keys, Limits & Plans
If you're building a commercial API and want to manage API keys, track usage, and set limits without building it from scratch — check out Limitly.
It’s a plug-and-play API access manager that works great with FastAPI.
🚀 Final Thoughts
This approach is simple and scalable for small to medium APIs. For more advanced use cases, you can:
- Store keys in a database
- Add rate-limiting
- Track usage per key
- Disable compromised keys dynamically
Protect your API early — it’s better than handling abuse later.
Happy coding! 🧑💻
Top comments (0)