The responses and response_model params for the route decorators seem to be broken for non-trivial data types.
#12373
-
First Check
Commit to Help
Example Code"""FastAPI StreamingResponse pydantic error example."""
from collections.abc import AsyncGenerator
from fastapi import FastAPI
from fastapi import status as fastapi_status
from fastapi.responses import StreamingResponse
app = FastAPI()
async def fake_video_streamer() -> AsyncGenerator[bytes]:
for _ in range(10):
yield b"some fake video bytes"
# This works (I know the response_model is redundant).
# @app.get(
# "/",
# status_code=fastapi_status.HTTP_200_OK,
# responses={
# 200: {
# "description": "Good",
# "model": list[str],
# },
# },
# response_model=list[str],
# )
# async def main() -> list[str]:
# return ["a", "b", "c"]
# ------------------------------------------------------------------------------------------------ #
# This causes a pydantic error.
# - Any combination of the `responses` and `response_model` flags causes the error.
# - It does work without the `responses` and `response_model` flags.
@app.get(
"/",
status_code=fastapi_status.HTTP_200_OK,
responses={
200: {
"description": "Good",
"model": StreamingResponse,
},
},
response_model=StreamingResponse,
)
async def main() -> StreamingResponse:
return StreamingResponse(fake_video_streamer())DescriptionThe example is a modified version of the Previously, I would you the OutputOperating SystemmacOS Operating System DetailsNo response FastAPI Version0.115.0 Pydantic Version2.9.2 Python Version3.12.5 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The above is inclorrect. Since you return the instance of You can still specify response model when using @app.get(
"/",
status_code=fastapi_status.HTTP_200_OK,
response_model=list[str], # For documentation only
)
async def main() -> StreamingResponse:
return StreamingResponse(generate_list()) # FastAPI will not validate response against the response model |
Beta Was this translation helpful? Give feedback.
The above is inclorrect.
StreamingResponseis response class, but not response model.Since you return the instance of
StreamingResponse(which is a sub-class ofResponseclass). FastAPI will not validate response (https://fastapi.tiangolo.com/advanced/response-directly/).You can still specify response model when using
StreamingResponse, but it will be for documentation purpose only. You are in charge of the response validation: