XAPI Guard is FastAPI middleware that protects your API endpoints by validating the X-API-Key header. It's designed in a decorator style, so you can annotate your FastAPI endpoints with @guard.protect
to protect them.
- Protect your FastAPI endpoints by validating the
X-API-Key
header. - Use
@guard.protect
to secure specific routes or entire routers. - Easily configure which routes require protection and which are public.
- Automatically handle unauthorized access with appropriate error messages.
- Support for OpenAPI/Swagger documentation with protected routes.
Choose your preferred installation method:
poetry add xapi-guard-middleware
pip install xapi-guard-middleware
For security best practices, XAPI Guard recommends using 128-bit API keys with mixed letters and numbers. You can generate a secure API key using one of these methods:
-
Using the recommended online generator:
- Visit generate-random.org/api-key-generator
- Select "128-bit" length
- Choose "Mixed letters & Numbers" type (recommended)
- Click "Generate API Keys"
-
Using Python's secrets module (recommended for production):
import secrets
import string
def generate_api_key(length=64):
alphabet = string.ascii_letters + string.digits
key = "".join(secrets.choice(alphabet) for _ in range(length))
return f"sk_{key}"
api_key = generate_api_key()
print(api_key)
You can run this script from scripts/generator.py
:
python3 scripts/generator.py
# Output: sk_mpo0ad7e4AlqYyinUZenCaXlerWr48aG30kgjGeXxFrEvH895C2qUtISBLIgc1Ek
Example API key format:
sk_mpo0ad7e4AlqYyinUZenCaXlerWr48aG30kgjGeXxFrEvH895C2qUtISBLIgc1Ek
Security Tips:
- Always use 128-bit or longer keys for production environments
- Avoid using special characters to ensure compatibility across different systems
- Store API keys securely and never commit them to version control
- Rotate API keys periodically for enhanced security
from fastapi import FastAPI, Depends, APIRouter
from xapi_guard_middleware import XAPIGuardMiddleware
app = FastAPI(title="XAPI Guard Middleware Example")
guard = XAPIGuardMiddleware(x_api_key="sk_85BnHrWHbLEKty7gNXVSwP385eLZipN6UvlSRjcvOXucwWq7MqAmvB5PhQ5xhy5n0uVFxluUuomCzRpoNuL7ffEnMApAs9hwIUDtoWN1je9ZYIkqAz6qrVSWdbZs8")
# Routers for different route groups
admin_router = APIRouter(dependencies=[Depends(guard.protect)])
settings_router = APIRouter(dependencies=[Depends(guard.protect)])
public_router = APIRouter()
# General routes
@app.get("/", tags=["General"])
async def root():
"""Root endpoint returning a welcome message."""
return {"message": "Hello World"}
@app.get("/health", tags=["General"])
async def health():
"""Health check endpoint to verify service status."""
return {"status": "healthy"}
# Public routes
@public_router.get("/public", tags=["Public"])
async def public():
"""Public endpoint accessible to everyone."""
return {"message": "This is a public endpoint accessible to everyone."}
# Admin routes
@admin_router.get("/admin", tags=["Admin"])
async def admin():
"""Admin area endpoint."""
return {"message": "Welcome to the admin area!"}
# Settings routes
@settings_router.get("/settings", tags=["Settings"])
async def settings():
"""Settings page, accessible only to authorized users."""
return {"message": "Settings page, accessible only to authorized users."}
# Include the routers in the main app
app.include_router(public_router)
app.include_router(admin_router, prefix="/secure")
app.include_router(settings_router, prefix="/secure")
$ poetry install
$ poetry shell
$ poetry run uvicorn examples.app:app --reload
- The FastAPI app is running on http://localhost:8000
# Unauthorized request (invalid API key)
curl -X GET http://localhost:8000/secure/admin -H "X-API-Key: wrong-key"
# {
# "detail": {
# "code": "INVALID_API_KEY",
# "message": "Invalid API key"
# }
# }
# Status code: 403
# Authorized request
curl -X GET http://localhost:8000/secure/admin -H "X-API-Key: YOUR_API_KEY"
# Response: {"message": "Welcome to the admin area!"}
# Status code: 200
Contributions are welcome! Please open an issue or submit a pull request.
This project is licensed under the MIT License. See the LICENSE file for details.