Cannot use a pydantic `dataclass` nested in a `BaseModel` as a `response_model`
See original GitHub issueFirst Check
- I added a very descriptive title to this issue.
- I used the GitHub search to find a similar issue and didn’t find it.
- I searched the FastAPI documentation, with the integrated search.
- I already searched in Google “How to X in FastAPI” and didn’t find any information.
- I already read and followed all the tutorial in the docs and didn’t find an answer.
- I already checked if it is not related to FastAPI but to Pydantic.
- I already checked if it is not related to FastAPI but to Swagger UI.
- I already checked if it is not related to FastAPI but to ReDoc.
Commit to Help
- I commit to help with one of those options 👆
Example Code
from fastapi import FastAPI
from pydantic import BaseModel
from pydantic.dataclasses import dataclass
app = FastAPI()
@dataclass
class Item:
name: str
class Box(BaseModel):
item: Item
@app.get("/item", response_model=Item)
async def item() -> Item:
return Item(name="test")
@app.get("/box", response_model=Box)
async def box() -> Box:
return Box(item=await item())
Description
The item
endpoint works fine, but the box
one fails with a ValidationError
:
$ uvicorn main:app
INFO: Started server process [13673]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: 127.0.0.1:46020 - "GET /docs HTTP/1.1" 200 OK
INFO: 127.0.0.1:46020 - "GET /openapi.json HTTP/1.1" 200 OK
INFO: 127.0.0.1:46020 - "GET /item HTTP/1.1" 200 OK
INFO: 127.0.0.1:46020 - "GET /box HTTP/1.1" 500 Internal Server Error
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/home/guest/.local/share/virtualenvs/tmp.KhplXQz0Am-XrtSmM4b/lib/python3.10/site-packages/uvicorn/protocols/http/h11_impl.py", line 373, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/home/guest/.local/share/virtualenvs/tmp.KhplXQz0Am-XrtSmM4b/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
return await self.app(scope, receive, send)
File "/home/guest/.local/share/virtualenvs/tmp.KhplXQz0Am-XrtSmM4b/lib/python3.10/site-packages/fastapi/applications.py", line 208, in __call__
await super().__call__(scope, receive, send)
File "/home/guest/.local/share/virtualenvs/tmp.KhplXQz0Am-XrtSmM4b/lib/python3.10/site-packages/starlette/applications.py", line 112, in __call__
await self.middleware_stack(scope, receive, send)
File "/home/guest/.local/share/virtualenvs/tmp.KhplXQz0Am-XrtSmM4b/lib/python3.10/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc
File "/home/guest/.local/share/virtualenvs/tmp.KhplXQz0Am-XrtSmM4b/lib/python3.10/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/home/guest/.local/share/virtualenvs/tmp.KhplXQz0Am-XrtSmM4b/lib/python3.10/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc
File "/home/guest/.local/share/virtualenvs/tmp.KhplXQz0Am-XrtSmM4b/lib/python3.10/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/home/guest/.local/share/virtualenvs/tmp.KhplXQz0Am-XrtSmM4b/lib/python3.10/site-packages/starlette/routing.py", line 656, in __call__
await route.handle(scope, receive, send)
File "/home/guest/.local/share/virtualenvs/tmp.KhplXQz0Am-XrtSmM4b/lib/python3.10/site-packages/starlette/routing.py", line 259, in handle
await self.app(scope, receive, send)
File "/home/guest/.local/share/virtualenvs/tmp.KhplXQz0Am-XrtSmM4b/lib/python3.10/site-packages/starlette/routing.py", line 61, in app
response = await func(request)
File "/home/guest/.local/share/virtualenvs/tmp.KhplXQz0Am-XrtSmM4b/lib/python3.10/site-packages/fastapi/routing.py", line 234, in app
response_data = await serialize_response(
File "/home/guest/.local/share/virtualenvs/tmp.KhplXQz0Am-XrtSmM4b/lib/python3.10/site-packages/fastapi/routing.py", line 137, in serialize_response
raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 1 validation error for Box
response -> item
value is not a valid dict (type=type_error.dict)
Operating System
Linux
Operating System Details
No response
FastAPI Version
0.71.0
Python Version
3.10.1
Additional Context
No response
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:6
Top Results From Across the Web
Dataclasses - pydantic
If you don't want to use pydantic's BaseModel you can instead get the same data ... Nested dataclasses are supported both in dataclasses...
Read more >How to include non-pydantic classes in fastapi responses?
I want to include a custom class into a route's response. I'm mostly using nested pydantic.BaseModel ...
Read more >Response Model - FastAPI
FastAPI will use this response_model to: Convert the output data to its type declaration. Validate the data. Add a JSON Schema for the...
Read more >Validate A Complex Nested Data Structure With Pydantic?
Deserialization of unknown JSON structures possible using method GENERATE into on the fly created data types; On JSON to ABAP transformation following ...
Read more >tiangolo/fastapi - Gitter
I am using pydantic dataclasses as part of a nested response model (the top-level class is a pydantic.BaseModel , but there is an...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
this is a bug https://github.com/samuelcolvin/pydantic/issues/3764
Yes, I did. Like I explained above, those were my findings and I believe
_prepare_response_content
might need an improvement. If you are going to create a PR that can fix the issue it would be great and I would be glad to see. Apart from that, until having seen a better explanation I don’t have much to say.