-
Notifications
You must be signed in to change notification settings - Fork 1
/
example.py
59 lines (47 loc) · 1.52 KB
/
example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""Implement the example in the readme."""
import functools
import inspect
import sys
from typing import List
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
@app.get("/has_author")
async def has_author(identifier: str) -> bool:
"""
Check if the author exists in the database.
"""
return identifier in ["Margaret Cavendish", "Jane Austen"]
@app.get("/categories")
async def get_categories() -> List[str]:
"""
Retrieve the list of available categories.
"""
return ["sci-fi", "romance"]
class Book(BaseModel):
identifier: str
author: str
@app.get("/books/", response_model=List[Book])
async def get_books(category: str):
"""
Retrieve the books of the given category from the database.
"""
if category not in await get_categories():
raise HTTPException(status_code=404, detail="Category not found")
async def implementation():
if category == "sci-fi":
return [
Book(identifier="The Blazing World", author="Margaret Cavendish")
]
elif category == "romance":
return [
Book(identifier="Pride and Prejudice", author="Jane Austen")
]
else:
raise AssertionError(category)
result = await implementation()
for book in result:
if not await has_author(identifier=book.author):
raise HTTPException(
status_code=500,
detail=f"Unexpected author in the result: {book.author}")