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