Add example and explanation for APIKeyHeader in security docs

This commit is contained in:
Gaurav 2025-08-25 17:07:52 +05:30
parent 9cf7b70d7b
commit ee831bb1ac
1 changed files with 29 additions and 0 deletions

View File

@ -34,6 +34,35 @@ from fastapi.security import (
::: fastapi.security.APIKeyHeader
### Using APIKeyHeader
`APIKeyHeader` is a security tool for extracting API keys from HTTP headers.
Heres a simple example of how to use it in FastAPI:
```python
from fastapi import FastAPI, Security, HTTPException
from fastapi.security import APIKeyHeader
from starlette.status import HTTP_403_FORBIDDEN
app = FastAPI()
API_KEY = "mysecretapikey"
API_KEY_NAME = "access_token"
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
@app.get("/secure-data")
async def secure_data(api_key: str = Security(api_key_header)):
if api_key == API_KEY:
return {"message": "Secure data accessed"}
else:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="Could not validate API key"
)
::: fastapi.security.APIKeyQuery
## HTTP Authentication Schemes