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-02-12 18:15 +0000
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-12 18:15 +0000
1import random 1abc
2from typing import Annotated 1abc
4from fastapi import FastAPI 1abc
5from pydantic import AfterValidator 1abc
7app = FastAPI() 1abc
9data = { 1abc
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): 1abc
17 if not id.startswith(("isbn-", "imdb-")): 1mdenfgohi
18 raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"') 1mno
19 return id 1defghi
22@app.get("/items/") 1abc
23async def read_items( 1abc
24 id: Annotated[str | None, AfterValidator(check_valid_id)] = None,
25):
26 if id: 1dejfgkhil
27 item = data.get(id) 1defghi
28 else:
29 id, item = random.choice(list(data.items())) 1jkl
30 return {"id": id, "name": item} 1dejfgkhil