Debian Codegraph @

docs_src/dependencies/tutorial008b_an_py310.py

raw
1 from typing import Annotated
2
3 from fastapi import Depends, FastAPI, HTTPException
4
5 app = FastAPI()
6
7
8 data = {
9 "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"},
10 "portal-gun": {"description": "Gun to create portals", "owner": "Rick"},
11 }
12
13
14 class OwnerError(Exception):
15 pass
16
17
18 def get_username():
19 try:
20 yield "Rick"
21 except OwnerError as e:
22 raise HTTPException(status_code=400, detail=f"Owner error: {e}")
23
24
25 @app.get("/items/{item_id}")
26 def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
27 if item_id not in data:
28 raise HTTPException(status_code=404, detail="Item not found")
29 item = data[item_id]
30 if item["owner"] != username:
31 raise OwnerError(username)
32 return item