-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathreadme_quickstart.py
More file actions
55 lines (36 loc) · 1.25 KB
/
Copy pathreadme_quickstart.py
File metadata and controls
55 lines (36 loc) · 1.25 KB
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
"""The README Quickstart, runnable end to end.
One route maps two exceptions to two statuses.
Short form maps a status; ``rule()`` adds a side effect.
The default translator renders both as ``{"error": ...}``.
Run: python -m examples.readme_quickstart
- GET /stock/ -> 401 {"error": "authentication required"}
- GET /stock/?user_id=1 -> 404 {"error": "user 1 not found"}
"""
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi_error_map import ErrorAwareRouter, rule
class AuthenticationError(Exception): ...
class UserNotFoundError(Exception): ...
class Stock(BaseModel):
available: int
def notify(err: Exception) -> None:
print(f"lookup failed: {err}")
def make_app() -> FastAPI:
router = ErrorAwareRouter()
@router.get(
"/stock/",
error_map={
AuthenticationError: 401,
UserNotFoundError: rule(404, on_error=notify),
},
)
def check_stock(user_id: int = 0) -> Stock:
if user_id == 0:
raise AuthenticationError("authentication required")
raise UserNotFoundError(f"user {user_id} not found")
app = FastAPI()
app.include_router(router)
return app
if __name__ == "__main__":
import uvicorn
uvicorn.run(make_app())