Debian Codegraph @

docs_src/query_params_str_validations/tutorial015_an_py310.py

raw
1 import random
2 from typing import Annotated
3
4 from fastapi import FastAPI
5 from pydantic import AfterValidator
6
7 app = FastAPI()
8
9 data = {
10 "isbn-9781529046137": "The Hitchhiker's Guide to the Galaxy",
11 "imdb-tt0371724": "The Hitchhiker's Guide to the Galaxy",
12 "isbn-9781439512982": "Isaac Asimov: The Complete Stories, Vol. 2",
13 }
14
15
16 def check_valid_id(id: str):
17 if not id.startswith(("isbn-", "imdb-")):
18 raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"')
19 return id
20
21
22 @app.get("/items/")
23 async def read_items(
24 id: Annotated[str | None, AfterValidator(check_valid_id)] = None,
25 ):
26 if id:
27 item = data.get(id)
28 else:
29 id, item = random.choice(list(data.items()))
30 return {"id": id, "name": item}