This commit is contained in:
Gaurav Patil 2025-12-16 21:07:32 +00:00 committed by GitHub
commit 4db2fd3833
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 29 additions and 0 deletions

View File

@ -34,6 +34,35 @@ from fastapi.security import (
::: fastapi.security.APIKeyHeader ::: 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 ::: fastapi.security.APIKeyQuery
## HTTP Authentication Schemes ## HTTP Authentication Schemes