-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI, HTTPException
from pydantic import BaseModel
# db mock object for simplicity
childs = [
{'id': 1, 'name': 'product1', 'barcode': '001'},
{'id': 2, 'name': 'product2', 'barcode': '002'},
{'id': 3, 'name': 'product3', 'barcode': '003'},
]
class ChildBase(BaseModel):
name: str
barcode: str
class ChildSchema(ChildBase):
id: int
class Config:
from_attributes = True
app = FastAPI()
@app.get('/childs/{child_id}', tags=['child'], response_model=ChildSchema, status_code=200)
def get_child(child_id: int):
child = next((item for item in childs if item["id"] == child_id), None)
if not child:
return HTTPException(status_code=404, detail='Child not found')
return child DescriptionTried to simplify my code. Originally I query a database instead of a mock object but the result is the same. I start testing the endpoint in the Swagger UI, passing the child_id parameter.
And if the child_id doesn't exists, I expect this response body:
However, the latter doesn't happen. Instead, I get an Internal Server Error with the following message in the logs:
This is solved pretty easily if I remove the I understand there are some mechanism to override the exception handling methods in FastAPI, but I'm a bit lost and confused with some concepts. Is there something I'm missing? Or is there a better way of doing this with both the Operating SystemLinux, Windows Operating System DetailsNo response FastAPI Version0.111.0 Pydantic Version2.7.1 Python Version3.10.12 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Raise, not return. |
Beta Was this translation helpful? Give feedback.
Raise, not return.