This commit is contained in:
Chris Paul 2025-12-16 21:07:32 +00:00 committed by GitHub
commit e3b30cb00a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 30 additions and 0 deletions

View File

@ -0,0 +1,28 @@
# APIKey Header
FastAPI supports using **API keys** as an alternative to OAuth2/JWT.
This is useful when you want to quickly secure an endpoint with a simple key check.
---
## 📘 Example
```python
from fastapi import FastAPI, Security, HTTPException, Depends
from fastapi.security.api_key import APIKeyHeader
app = FastAPI()
API_KEY = "supersecretapikey"
api_key_header = APIKeyHeader(name="X-API-Key")
def get_api_key(api_key: str = Security(api_key_header)):
if api_key != API_KEY:
raise HTTPException(status_code=403, detail="Could not validate API KEY")
return api_key
@app.get("/secure-data/")
def secure_data(api_key: str = Depends(get_api_key)):
return {"message": "You have access to secure data!"}
```

View File

@ -104,3 +104,5 @@ FastAPI provides several tools for each of these security schemes in the `fastap
In the next chapters you will see how to add security to your API using those tools provided by **FastAPI**.
And you will also see how it gets automatically integrated into the interactive documentation system.
- [APIKey Header](api-key.md)