from fastapi import Header, HTTPException, status, Depends
# Dependency 1: Extract API Key
def get_api_key(x_api_key: str | None = Header(None)):
if not x_api_key:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Missing API Key header"
)
return x_api_key
# Dependency 2: Verify Key belongs to Admin (Depends on Dependency 1)
def verify_admin_key(api_key: str = Depends(get_api_key)):
if api_key != "secret-admin-key":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Forbidden: Admin privileges required"
)
return "Admin-User"
# Use in Endpoint
@app.delete("/employees/{emp_id}")
def delete_employee(emp_id: int, admin_user: str = Depends(verify_admin_key)):
# This route only executes if both dependencies pass
return {"message": f"Employee {emp_id} deleted successfully by {admin_user}"}