-
First Check
Commit to Help
Example Codefrom fastapi import Body, Depends, FastAPI, HTTPException, Path, Query, Request
from pydantic import BaseModel, Field, ValidationError
from pprint import pprint as pp
app = FastAPI()
class MetadataOut(BaseModel):
"""
Model for Metadata
"""
region: str = Field(
...,
title="region",
description="region - one of dc00|dc01|dc02",
regex=r"^(dc00|dc01|dc02)$",
)
@app.get("/api/v1/metadata/fail", response_model=MetadataOut)
def metadatafail():
return {"region": "whoops"}
@app.get("/api/v1/metadata/failwitherror", response_model=MetadataOut)
def metadatafailwitherror():
try:
return MetadataOut(region="whoops")
except ValidationError as e:
pp(e)
raise HTTPException(status_code=422, detail=e.errors())
@app.get("/api/v1/metadata/pass", response_model=MetadataOut)
def metadatapass():
return {"region": "dc01"}
if __name__ == "__main__":
uvicorn.run(
app,
host="0.0.0.0",
port=8080,
) DescriptionI am asking this as a question because I am hoping that I just need to adjust my code a bit. I am expecting when the response validation fails fastapi would return a 422 error and the pydantic descriptive error just like input works. The only way I have gotten a half way decent return is to do what you see in the /api/v1/metadata/failwitherror endpoint. Operating SystemLinux Operating System DetailsNo response FastAPI Version0.74.1 Python VersionPython 3.8.10 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 10 comments
-
Can you provide full error trace? ie, Traceback |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
This behaviour is intentionally and explained here in the docs: https://fastapi.tiangolo.com/tutorial/handling-errors/#requestvalidationerror-vs-validationerror TLDR: if your response cannot be casted as the pydantic model you've declared, that is considered a logic flaw and hence a 500 is thrown. |
Beta Was this translation helpful? Give feedback.
-
ok cool thank you |
Beta Was this translation helpful? Give feedback.
-
To be complete: a 422 is basically saying that the entity as provided by the client is unprocessable; so it's the clients fault. Rendering a response and incurring an error while doing that, is by definition a server error, and thus it will produce a HTTP 500. The way you've caught and handled the exception is an option (like in If your response model is dependant on an input, you might want to cast it your self in a try/except block, rather than having FastAPI doing it by means of If this answers your question, please close the issue. |
Beta Was this translation helpful? Give feedback.
-
@JarroVGIT unfortunately without the response_model= the swagger interface doesn't self-document the return. |
Beta Was this translation helpful? Give feedback.
-
@JarroVGIT thank you for answering so effectively. :) |
Beta Was this translation helpful? Give feedback.
-
@JarroVGIT my turn to be complete :) this is the input:
|
Beta Was this translation helpful? Give feedback.
-
Thanks for the help here @iudeen and @JarroVGIT ! 👏 🙇 Thanks for reporting back and closing the issue @JoeyG1973 👍 |
Beta Was this translation helpful? Give feedback.
-
another option is to move the said exception logic above/outside your try and exception block |
Beta Was this translation helpful? Give feedback.
This behaviour is intentionally and explained here in the docs:
https://fastapi.tiangolo.com/tutorial/handling-errors/#requestvalidationerror-vs-validationerror
TLDR: if your response cannot be casted as the pydantic model you've declared, that is considered a logic flaw and hence a 500 is thrown.