defget_api_key( api_key_query: str = Security(api_key_query), api_key_header: str = Security(api_key_header), ) -> str: """Retrieve and validate an API key from the query parameters or HTTP header. Args: api_key_query: The API key passed as a query parameter. api_key_header: The API key passed in the HTTP header. Returns: The validated API key. Raises: HTTPException: If the API key is invalid or missing. """ if api_key_query in API_KEYS: return api_key_query if api_key_header in API_KEYS: return api_key_header raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or missing API Key", )
Step 3: Secure the Routes
1 2 3 4 5 6 7 8 9 10 11
app = FastAPI()
@app.get("/public") defpublic(): """A public endpoint that does not require any authentication.""" return"Public Endpoint"
@app.get("/private") defprivate(api_key: str = Security(get_api_key)): """A private endpoint that requires a valid API key to be provided.""" returnf"Private Endpoint. API Key: {api_key}"
defget_api_key( api_key_query: str = Security(api_key_query), api_key_header: str = Security(api_key_header), ) -> str: """Retrieve and validate an API key from the query parameters or HTTP header. Args: api_key_query: The API key passed as a query parameter. api_key_header: The API key passed in the HTTP header. Returns: The validated API key. Raises: HTTPException: If the API key is invalid or missing. """ if api_key_query in API_KEYS: return api_key_query if api_key_header in API_KEYS: return api_key_header raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or missing API Key", )
app = FastAPI()
@app.get("/public") defpublic(): """A public endpoint that does not require any authentication.""" return"Public Endpoint"
@app.get("/private") defprivate(api_key: str = Security(get_api_key)): """A private endpoint that requires a valid API key to be provided.""" returnf"Private Endpoint. API Key: {api_key}"