From ee831bb1ac47d39cdf2fffa1be96168e4d6afc77 Mon Sep 17 00:00:00 2001 From: Gaurav Date: Mon, 25 Aug 2025 17:07:52 +0530 Subject: [PATCH] Add example and explanation for APIKeyHeader in security docs --- docs/en/docs/reference/security/index.md | 29 ++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/docs/en/docs/reference/security/index.md b/docs/en/docs/reference/security/index.md index 9a5c5e15f..9ad68dfc5 100644 --- a/docs/en/docs/reference/security/index.md +++ b/docs/en/docs/reference/security/index.md @@ -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. + +Here’s 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