Complete worked example
python
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi.testclient import TestClient
def inspect_example(request):
app = FastAPI()
bearer = HTTPBearer(auto_error=False)
tokens = {"demo-alice": "alice", "demo-bob": "bob"}
records = {1: {"owner": "alice", "title": "QA", "private_note": "hidden"}}
def principal(credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(bearer)]):
if credentials is None or credentials.credentials not in tokens:
raise HTTPException(401, "Sign in", headers={"WWW-Authenticate": "Bearer"})
return tokens[credentials.credentials]
@app.get("/roles/{role_id}")
def read(role_id: int, user: Annotated[str, Depends(principal)]):
record = records.get(role_id)
if record is None or record["owner"] != user:
raise HTTPException(404, "Role not found")
return {"id": role_id, "title": record["title"]}
headers = {} if "token" not in request else {"Authorization": "Bearer " + request["token"]}
with TestClient(app) as client:
response = client.get(f"/roles/{request.get('id', 1)}", headers=headers)
return {"status": response.status_code, "body": response.json()}- Reasoning
- HTTPBearer extracts the credential representation. The dependency rejects missing or unknown demo credentials with 401 and a bearer challenge. After identity resolution, the endpoint checks record existence and ownership. The chosen policy returns 404 for both an absent object and an object belonging to someone else. The local record contains a private note, but the success response is a deliberately small mapping. The helper sends an optional Authorization header through TestClient and compares the real status and body. No real account, token, email or live user record is involved.