Debian Codegraph @

docs_src/app_testing/app_b_py310/main.py

raw
1 from fastapi import FastAPI, Header, HTTPException
2 from pydantic import BaseModel
3
4 fake_secret_token = "coneofsilence"
5
6 fake_db = {
7 "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"},
8 "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"},
9 }
10
11 app = FastAPI()
12
13
14 class Item(BaseModel):
15 id: str
16 title: str
17 description: str | None = None
18
19
20 @app.get("/items/{item_id}", response_model=Item)
21 async def read_main(item_id: str, x_token: str = Header()):
22 if x_token != fake_secret_token:
23 raise HTTPException(status_code=400, detail="Invalid X-Token header")
24 if item_id not in fake_db:
25 raise HTTPException(status_code=404, detail="Item not found")
26 return fake_db[item_id]
27
28
29 @app.post("/items/")
30 async def create_item(item: Item, x_token: str = Header()) -> Item:
31 if x_token != fake_secret_token:
32 raise HTTPException(status_code=400, detail="Invalid X-Token header")
33 if item.id in fake_db:
34 raise HTTPException(status_code=409, detail="Item already exists")
35 fake_db[item.id] = item.model_dump()
36 return item