11from typing import Union
22
3- from fastapi import FastAPI
3+ from fastapi import FastAPI , HTTPException
4+ from pydantic import BaseModel
45
56app = FastAPI ()
67
78
89@app .get ("/" )
910def read_root ():
1011 return {"Hello" : "World" }
12+ class Creature (BaseModel ):
13+ id : int
14+ family : str
15+ common_name : str
16+ class Config :
17+ schema_extra = {
18+ "example" : {
19+ "id" : 1 ,
20+ "family" : "Amphibian" ,
21+ "name" : "Frog"
22+ }
23+ }
1124
25+ class AuthenticationError (HTTPException ):
26+ def __init__ (self , detail : str ):
27+ super ().__init__ (status_code = 401 , detail = detail )
1228
13- @app .get ("/items/{item_id}" )
29+
30+ creatures : list [Creature ] = [Creature (id = 1 , family = "Amphibian" , common_name = "Frog" )]
31+
32+ @app .get ("/creatures/{creature_id}" )
1433def read_item (item_id : int , q : Union [str , None ] = None ):
15- return {"item_id" : item_id , "q" : q }
34+ return {"item_id" : item_id , "q" : q }
35+
36+ @app .post ("/create_amphibian" )
37+ def create_amphibian (creature : Creature , user_level : int , throws : bool = False ) -> bool :
38+ if throws :
39+ raise Exception ("This is an unexpected exception" )
40+ if creature .family != "Amphibian" : # validation error not caught by FastAPI
41+ raise HTTPException (status_code = 400 , detail = "Only amphibians allowed" )
42+ if user_level < 2 :
43+ raise AuthenticationError (status_code = 403 , detail = "You are not admin" )
44+ creatures .append (creature )
45+ return True
0 commit comments