response_model not working for list[] responses
#10040
-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI
app = FastAPI()
class Item(BaseModel):
name: str
price: float
description: str
@app.post("/items/", response_model=list[Item], response_model_exclude={"price",})
async def create_item(item: Item):
return [item]DescriptionAfter I call the [
{
"name": "string",
"description": "string"
}
]but I am getting [
{
"name": "string",
"price": 0,
"description": "string"
}
]Is there any solution for this ? Operating SystemmacOS Operating System DetailsNo response FastAPI Version0.101.0 Pydantic Version2.1.1 Python Version3.11 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
|
It worked with fastapi version 0.92.0, pydantic 1.10.5, and python 3.10, though I guess fastapi version matters. Most probably, I think we need to provide |
Beta Was this translation helpful? Give feedback.
-
|
Hi! It's not possible to exclude when the response is a list, also I recommend data filtering. See the tip This should work as expected: from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class ItemBase(BaseModel):
name: str
description: str
class CreateItem(ItemBase):
price: float
class ShowItem(ItemBase):
pass
@app.post("/items/", response_model=list[ShowItem])
async def create_item(item: CreateItem):
return [item] |
Beta Was this translation helpful? Give feedback.
-
|
It seems like you are trying to exclude the "price" field from the response model when using FastAPI and Pydantic. However, in your current code, the "price" field is still included in the response. To exclude a field from the response model, you can use the response_model_exclude parameter when defining the route. In your code, you are using it correctly, but there might be a version issue or a mistake in the usage. In FastAPI 0.101.0, the response_model_exclude parameter should be a set of field names to exclude. However, it seems that it's not working as expected in your case. Here are a few things you can try to resolve the issue: Update FastAPI and Pydantic: Ensure that you are using the latest versions of FastAPI and Pydantic. Newer versions may have fixed this issue. Use a List as a Response Model: Instead of using list[Item] as the response model, try using a List of dictionaries. You can manually create the response format you want. For example: app = FastAPI() class Item(BaseModel): @app.post("/items/", response_model=list[dict], response_model_exclude={"price"}) |
Beta Was this translation helpful? Give feedback.
Hi!
It's not possible to exclude when the response is a list, also I recommend data filtering.
See the tip
This should work as expected: