Fastapi: [BUG] Nested pydantic model in response model doesn't filter additional data

Created on 11 Jan 2020  路  4Comments  路  Source: tiangolo/fastapi

Describe the bug

In Response Model documentation, there is an example for FastAPI will take care of filtering out all the data that is not declared in the output model. However, this doesn't happen for a nested model.

To Reproduce

  1. Create a file with:
from fastapi import FastAPI, Depends
from pydantic import BaseModel

app = FastAPI()


class ModelB(BaseModel):
    username: str


class ModelC(ModelB):
    password: str


class ModelA(BaseModel):
    name: str
    description: str = None
    model_b: ModelB


async def get_model_c() -> ModelC:
    return ModelC(username="test-user", password="test-password")


@app.get("/model", response_model=ModelA)
async def get_model_a(model_c=Depends(get_model_c)):
    return {"name": "model-a-name", "description": "model-a-desc", "model_b": model_c}
  1. Open the browser and call the endpoint /model.
  2. It returns a JSON with {"name":"model-a-name","description":"model-a-desc","model_b":{"username":"test-user","password":"test-password"}}.
  3. But I expected it to return {"name":"model-a-name","description":"model-a-desc","model_b":{"username":"test-user"}}.

Expected behavior

Filtering should be done for nested model attributes too.

Environment

  • OS: Ubuntu 18.04.3 LTS
  • FastAPI 0.45.0
  • Python 3.8.1
bug

Most helpful comment

Yep, this really needs to be fixed. I haven't had much free time lately but I'll try to get around to fixing this soon.

As a short term workaround, it should work properly if you call return jsonable_encoder(<current response>) where jsonable_encoder is fastapi.encoders.jsonable_encoder. But obviously it would be better if this wasn't required.

All 4 comments

Yep, this really needs to be fixed. I haven't had much free time lately but I'll try to get around to fixing this soon.

As a short term workaround, it should work properly if you call return jsonable_encoder(<current response>) where jsonable_encoder is fastapi.encoders.jsonable_encoder. But obviously it would be better if this wasn't required.

Thanks for the easy to replicate and test report @sagrawal-idrc ! :bug:

And thanks @dmontagu for the help here :muscle:

And yeah, @chbndrhnns , it was the same issue.

It should be fixed by #889, just released in the latest version 0.47.1.

Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

danielgtaylor picture danielgtaylor  路  3Comments

vnwarrior picture vnwarrior  路  3Comments

DrPyser picture DrPyser  路  3Comments

KoduIsGreat picture KoduIsGreat  路  3Comments

updatatoday picture updatatoday  路  3Comments