Coverage for docs_src/query_params_str_validations/tutorial015_an.py: 100%
17 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-05-05 00:03 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2025-05-05 00:03 +0000
1import random 1abcdef
2from typing import Union 1abcdef
4from fastapi import FastAPI 1abcdef
5from pydantic import AfterValidator 1abcdef
6from typing_extensions import Annotated 1abcdef
8app = FastAPI() 1abcdef
10data = { 1abcdef
11 "isbn-9781529046137": "The Hitchhiker's Guide to the Galaxy",
12 "imdb-tt0371724": "The Hitchhiker's Guide to the Galaxy",
13 "isbn-9781439512982": "Isaac Asimov: The Complete Stories, Vol. 2",
14}
17def check_valid_id(id: str): 1abcdef
18 if not id.startswith(("isbn-", "imdb-")): 1yghzijAklBmnCopDqr
19 raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"') 1yzABCD
20 return id 1ghijklmnopqr
23@app.get("/items/") 1abcdef
24async def read_items( 1abcdef
25 id: Annotated[Union[str, None], AfterValidator(check_valid_id)] = None,
26):
27 if id: 1ghsijtklumnvopwqrx
28 item = data.get(id) 1ghijklmnopqr
29 else:
30 id, item = random.choice(list(data.items())) 1stuvwx
31 return {"id": id, "name": item} 1ghsijtklumnvopwqrx