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
Describe the bug
Not sure if this should be a Feature request or a bug.
When returning a List of models, the response includes "unset" key/values whenresponse_model_exclude_unset is set toTrue.
To Reproduce
- Create a file with:
importpydanticfromfastapiimportFastAPIapp=FastAPI()classItem(pydantic.BaseModel):foobar:str="foobar"foo:strbar:str=NoneALL_ITEMS= [Item(foo="foo0"),Item(foo="foo1"),Item(foo="foo2")]@app .get("/items",response_model=List[Item],response_model_exclude_unset=True)defget_all_items():returnALL_ITEMS@app .get("/items/{item_index}",response_model=Item,response_model_exclude_unset=True)defget_item(item_index:int):returnALL_ITEMS[item_index]
- Open the browser and call the endpoint
/items. - It returns a JSON with...
[ {"foobar":"foobar","foo":"foo0","bar":null }, {"foobar":"foobar","foo":"foo1","bar":null }, {"foobar":"foobar","foo":"foo2","bar":null }]- But I expected it to return...
[ {"foo":"foo0" }, {"foo":"foo1" }, {"foo":"foo2" }]Expected behavior
I would expect/items and/items/{item_index} to return the same representation of an item.
Screenshots
Environment
- OS: Windows and MacOS
- FastAPI Version: 0.47.1
- Python version: 3.7.3
Additional context
The main thing I'm trying to achieve here is to exclude nulls when using List[MyModel]. Currently, the only workaround that I know of is to do one of the following.
- create a new response
AllItemsmodel and overloaddict() - create amiddleware that strips response nulls.
- use an arbitrary dict (I don't want to do this)
However, given the prevalence of API's that have a/<all_items>,/<single_item> I would think that usingresponse_model_exclude_unset orexclude_none is the more intuitive way to achieve this.

