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-05-05 00:03 +0000

1import random 1abcde

2from typing import Annotated, Union 1abcde

3 

4from fastapi import FastAPI 1abcde

5from pydantic import AfterValidator 1abcde

6 

7app = FastAPI() 1abcde

8 

9data = { 1abcde

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 

16def check_valid_id(id: str): 1abcde

17 if not id.startswith(("isbn-", "imdb-")): 1ufgvhiwjkxlmyno

18 raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"') 1uvwxy

19 return id 1fghijklmno

20 

21 

22@app.get("/items/") 1abcde

23async def read_items( 1abcde

24 id: Annotated[Union[str, None], AfterValidator(check_valid_id)] = None, 

25): 

26 if id: 1fgphiqjkrlmsnot

27 item = data.get(id) 1fghijklmno

28 else: 

29 id, item = random.choice(list(data.items())) 1pqrst

30 return {"id": id, "name": item} 1fgphiqjkrlmsnot