Skip to content

Commit 8dfaaae

Browse files
committed
Ex: add user retrieval endpoint to show validation error with description
1 parent 4ff1da2 commit 8dfaaae

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

examples/fastapi_usage.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,10 @@ class ApiKeyModel(BaseModel):
8080
api_key: str = Field(..., example="b2013852-1798-45fc-9bff-4b6916290f5b", description="Api Key.")
8181

8282

83+
class BodyModel(BaseModel):
84+
some_int_id: int = Field(..., description="The ID of the user")
85+
86+
8387
@app.get(
8488
"/user/{user_id}",
8589
response_model=ResponseModel[UserResponse],
@@ -119,6 +123,48 @@ async def get_user(x_user_id: str = Header(default=None),
119123
description="User fetched successfully.")
120124

121125

126+
127+
@app.post(
128+
"/user/{user_id}",
129+
response_model=ResponseModel[UserResponse],
130+
responses=APIResponse.default(),
131+
description='''
132+
Examples:
133+
- Get user with ID 1: `/user/1` - APIException: If the user ID is 1.
134+
- Get user with ID 2: `/user/2` - TypeError: If the user ID 2.
135+
- Get user with ID 3: `/user/3` - KeyError: If the user ID is 3.
136+
- Get user with ID 4: `/user/4` - IndexError: If the user ID is 4.
137+
- Get user with ID 5: `/user/5` - ZeroDivisionError: If the user ID is 5.
138+
- Get user with ID 6: `/user/6` - RuntimeError: If the user ID is 6.
139+
- Get user with ID 7: `/user/7` - Returns a valid user response.
140+
'''
141+
)
142+
async def get_user(user_id: int = Path(..., description="The ID of the user"),
143+
obj: BodyModel = ...,
144+
):
145+
if user_id == 1:
146+
raise APIException(
147+
error_code=CustomExceptionCode.USER_NOT_FOUND,
148+
http_status_code=404,
149+
)
150+
151+
if user_id == 2:
152+
raise TypeError("Invalid type provided.")
153+
if user_id == 3:
154+
raise KeyError("Missing key in dictionary.")
155+
if user_id == 4:
156+
raise IndexError("List index out of range.")
157+
if user_id == 5:
158+
raise ZeroDivisionError("Cannot divide by zero.")
159+
if user_id == 6:
160+
raise RuntimeError("Unexpected runtime issue.")
161+
162+
data = UserResponse(id=user_id, username="John Doe")
163+
return ResponseModel(data=data,
164+
description="User fetched successfully.")
165+
166+
167+
122168
@app.get(
123169
"/apikey",
124170
response_model=ResponseModel[ApiKeyModel],

0 commit comments

Comments
 (0)