Debian Codegraph @

docs_src/app_testing/app_b_an_py310/main.py

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