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.
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}
/model.{"name":"model-a-name","description":"model-a-desc","model_b":{"username":"test-user","password":"test-password"}}.{"name":"model-a-name","description":"model-a-desc","model_b":{"username":"test-user"}}.Filtering should be done for nested model attributes too.
I see this related to https://github.com/tiangolo/fastapi/issues/800
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.
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 isfastapi.encoders.jsonable_encoder. But obviously it would be better if this wasn't required.