Response Schema, Fastapi Streaming Responses for Documentation #11552
Answered
by
YuriiMotov
anantgupta129
asked this question in
Questions
-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
import json
import time
import asyncio
app = FastAPI()
class ErrorModel(BaseModel):
detail: str
def fake_json_streamer():
t0 = time.time()
for i in range(10):
print(f"Chunk being yielded (time {int((time.time()-t0)*1000)}ms)", flush=True)
yield json.dumps( {"message": "Hello World"}) + '\n'
time.sleep(0.5)
print(f"Over (time {int((time.time()-t0)*1000)}ms)", flush=True)
@app.get("/test", responses={500: {"model": ErrorModel}})
async def test():
try:
return StreamingResponse(fake_json_streamer(), media_type='text/event-stream')
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred while processing the request. {str(e)}") DescriptionHow to add schema for documentation to return streaming responses for text or json Operating SystemWindows Operating System DetailsNo response FastAPI Version0.109.2 Pydantic Version2.6.1 Python Version3.9.19 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Answered by
YuriiMotov
May 23, 2024
Replies: 1 comment 4 replies
-
See the additional responses section of the docs https://fastapi.tiangolo.com/advanced/additional-responses/ |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi!
If you are talking about clarifications for people who read docs, then you can add the description for
200
response:And if you are talking about specifying response type for client code generators, it requires more investigation..
Have you read discussions below?
OAI/OpenAPI-Specification#1576
OAI/OpenAPI-Specification#3730
OAI/OpenAPI-Specification#3769