Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Response model validations don't work#14380

Answeredbytiangolo
uncle-lv asked this question inQuestions
Discussion options

First Check

  • I added a very descriptive title here.
  • I used the GitHub search to find a similar question and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but toPydantic.
  • I already checked if it is not related to FastAPI but toSwagger UI.
  • I already checked if it is not related to FastAPI but toReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

fromfastapiimportFastAPIfrompydanticimportBaseModel,EmailStr,Fieldapp=FastAPI()classUserIn(BaseModel):email:EmailStrage:int=Field(default=18,gt=0)not_null:str@app.post("/user/",response_model=UserIn)asyncdefcreate_user(user:UserIn)->UserIn:user.email="invalid email"user.age=-1user.not_null=Nonereturnuser

Description

Thedoc says FastAPI will use this return type to validate the returned data:
image

But it doesn't work now.
image

Input validations work normally at the same time.
image

I'm not sure if this is a bug.

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.121.3

Pydantic Version

2.12.4

Python Version

3.12.7

Additional Context

No response

You must be logged in to vote

By default, Pydantic would expect to validate the external data received when creating a model, but it will assume that if you set values in your own code, that code is already correct and has correct values.

If you're in a situation where you cannot trust the assignment of the values in the model from inside your same code, you can change the Pydantic model to also validate on assignment:https://docs.pydantic.dev/latest/api/config/#pydantic.config.ConfigDict.validate_assignment

This way it will raise a validation error that will become a server error right on the first line where the first incorrect value is set.

For example:

fromfastapiimportFastAPIfrompydanticimportBaseModel,E…

Replies: 2 comments 4 replies

Comment options

Reproducible with pure Pydantic:

frompydanticimportBaseModel,EmailStr,Field,TypeAdapterclassUserIn(BaseModel):email:EmailStrage:int=Field(default=18,gt=0)not_null:struser=UserIn(email="I@example.com",age=25,not_null="Some value")user.email="invalid email"user.age=-1user.not_null=Nonetype_adapter=TypeAdapter(UserIn)res=type_adapter.validate_python(user,from_attributes=True)print(res)# email='invalid email' age=-1 not_null=None
You must be logged in to vote
3 replies
@YuriiMotov
Comment options

Or

res = UserIn.model_validate(user, from_attributes=True)
@uncle-lv
Comment options

Thanks a lot!

@YuriiMotov
Comment options

I think we should still do something with this. Maybe add a note in docs that FastAPI with Pydantic V2 will not re-validate response if you return the instance ofresponse_model

Comment options

By default, Pydantic would expect to validate the external data received when creating a model, but it will assume that if you set values in your own code, that code is already correct and has correct values.

If you're in a situation where you cannot trust the assignment of the values in the model from inside your same code, you can change the Pydantic model to also validate on assignment:https://docs.pydantic.dev/latest/api/config/#pydantic.config.ConfigDict.validate_assignment

This way it will raise a validation error that will become a server error right on the first line where the first incorrect value is set.

For example:

fromfastapiimportFastAPIfrompydanticimportBaseModel,EmailStr,Fieldapp=FastAPI()classUserIn(BaseModel):email:EmailStrage:int=Field(default=18,gt=0)not_null:strmodel_config= {"validate_assignment":True}@app.post("/user/",response_model=UserIn)asyncdefcreate_user(user:UserIn)->UserIn:user.email="invalid email"user.age=-1user.not_null=Nonereturnuser

Notice the:

model_config= {"validate_assignment":True}
You must be logged in to vote
1 reply
@YuriiMotov
Comment options

Running the same initial code (without{"validate_assignment": True}) with Pydantic V1 gives server error as expected:

    raise ResponseValidationError(fastapi.exceptions.ResponseValidationError: 3 validation errors:  {'loc': ('response', 'email'), 'msg': 'value is not a valid email address', 'type': 'value_error.email'}  {'loc': ('response', 'age'), 'msg': 'ensure this value is greater than 0', 'type': 'value_error.number.not_gt', 'ctx': {'limit_value': 0}}  {'loc': ('response', 'not_null'), 'msg': 'none is not an allowed value', 'type': 'type_error.none.not_allowed'}

So, we have:

  • Inconsistency between FastAPI with Pydantic v1 and v2 (I would even say regression)
  • Not fully correct statement in docs ("If the data is invalid (e.g. you are missing a field), it means that your app code is broken, not returning what it should, and it will return a server error")
Answer selected bytiangolo
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Labels
questionQuestion or problem
3 participants
@uncle-lv@tiangolo@YuriiMotov

[8]ページ先頭

©2009-2025 Movatter.jp