---
title: "Secure FastAPI APIs with API Key Authentication"
description: "Secure your FastAPI API using a shared secret."
canonicalUrl: "https://zuplo.com/use-cases/api-key-auth/python/fastapi/secure-header"
framework: "FastAPI"
language: "Python"
authStrategy: "shared secret header"
pageType: use-case
---

# Secure FastAPI APIs with API Key Authentication

Secure your FastAPI API using a shared secret.

## How Zuplo Handles It

Put Zuplo in front of your FastAPI backend to authenticate API keys and forward a shared secret header so your origin only accepts traffic from Zuplo.

## FastAPI Backend Code

```python
from fastapi import FastAPI, Request, HTTPException, status
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
import os
import hmac
import hashlib

app = FastAPI()

# Automatically redirect HTTP to HTTPS
app.add_middleware(HTTPSRedirectMiddleware)

def validate_shared_secret(request: Request):
    secret = request.headers.get("x-shared-secret")
    expected_secret = os.getenv("SHARED_SECRET")

    if expected_secret is None:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Server configuration error"
        )

    if secret is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="No secret provided"
        )

    # Use timing-safe comparison to prevent timing attacks
    if not hmac.compare_digest(secret, expected_secret):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid secret"
        )

@app.get("/protected")
async def protected_route(request: Request):
    validate_shared_secret(request)
    return {"message": "Access granted"}

# Example usage
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
```

## Example Request

```bash
curl -X GET \
  'https://your-api.zuplo.dev/your-route' \
  -H 'Authorization: Bearer YOUR_API_KEY'
```

## Learn More

- [API Key Authentication on Zuplo](https://zuplo.com/docs/policies/api-key-auth-inbound)
- [JWT Authentication on Zuplo](https://zuplo.com/docs/policies/open-id-jwt-auth-inbound)
- [All use cases](https://zuplo.com/use-cases)
