Coverage for docs_src / query_params_str_validations / tutorial015_an_py310.py: 100%
16 statements
« prev ^ index » next coverage.py v7.13.3, created at 2026-04-06 01:24 +0000
« prev ^ index » next coverage.py v7.13.3, created at 2026-04-06 01:24 +0000
1import random 1abcdefgh
2from typing import Annotated 1abcdefgh
4from fastapi import FastAPI 1abcdefgh
5from pydantic import AfterValidator 1abcdefgh
7app = FastAPI() 1abcdefgh
9data = { 1abcdefgh
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}
16def check_valid_id(id: str): 1abcdefgh
17 if not id.startswith(("isbn-", "imdb-")): 1tijouklvmn
18 raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"') 1twuv
19 return id 1ijoklmn
22@app.get("/items/") 1abcdefgh
23async def read_items( 1abcdefgh
24 id: Annotated[str | None, AfterValidator(check_valid_id)] = None,
25):
26 if id: 1ijpqklrmns
27 item = data.get(id) 1ijoklmn
28 else:
29 id, item = random.choice(list(data.items())) 1pqrs
30 return {"id": id, "name": item} 1ijpqklrmns