Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork8.7k
Closed
Description
Starting in 0.47.1, responses fail validation if they include any pydantic model objects that contain field aliases
You can work around this by explicitly calling.dict(by_alias=True) on the top-level response model object before returning it from the path operation function (see the example below). However, this is super unintuitive and makes the use of field aliases painful. In our codebase we use aliases extensively (viaConfig.alias_generator) to expose camelCase in our public APIs while keeping our internal field names snake_case, and this issue is a real hassle.
To Reproduce
- Create a
test.pyfile with:
importfastapiimportpydanticimportstarlette.testclientfromtypingimportListapp=fastapi.FastAPI()classItem(pydantic.BaseModel):my_value:int=pydantic.Field(...,alias='myValue')classRootResponse(pydantic.BaseModel):items:List[Item]=pydantic.Field(...)@app.get('/broken_1',response_model=RootResponse)asyncdefbroken_1():# embedded models don't work if they have aliased fieldsreturn {'items': [Item(myValue=5),Item(myValue=10)]}@app.get('/broken_2',response_model=RootResponse)asyncdefbroken_2():# making the top-level response a model instance doesn't helpreturnRootResponse(items=[Item(myValue=5),Item(myValue=10)])@app.get('/workaround',response_model=RootResponse)asyncdefworkaround():# workaround is to build a top-level model and then dict(by_alias=True)returnRootResponse(items=[Item(myValue=5),Item(myValue=10)]).dict(by_alias=True)withstarlette.testclient.TestClient(app)astest_client:forpathin ['/broken_1','/broken_2','/workaround']:try:print('-------------------------------------------')print(path)response=test_client.get(path)exceptExceptionasexc:print(exc)else:print('succeeded')
- Run
python3 test.pywith FastAPI 0.47.0. All 3 cases succeed. - Run
python3 test.pywith FastAPI 0.49.0. Only the "workaround" case succeeds.
Expected behavior
Model classes that include aliased fields (whether the alias is directly specified on the field as in the above example, or using a pydanticConfig.alias_generator) should be usable with the context of a response model.
Environment
- OS: Linux (Ubuntu 18.04)
- FastAPI Version: 0.47.1 and above
- Python version: 3.7, 3.8