I have a fastapi based service in python. I have a simple requirement: I have an end-point that does a lot of processing in the back-end, but has intermediate results. I want to return data in chunks. I am able to get my code to work if the return data is a string/byte-string. But if I want to return a json structure, I am just unable to make it work. Here's a simple code-snippet that I have tried. If i replace yield data with yield f"{json.dumps(data)}" I get the expected result, but the response data comes as a json string, which is not what I want.
Anyone knows what I am doing wrong here? Have consulted all kinds of sources with no success.
@app.get("/experimental/stream", summary="Experimenting with some streaming response stuff") async def stream_response():
async def stream_generator():
for i in range(10):
data = {
"iteration": i
}
yield data
time.sleep(1)
return(StreamingResponse(stream_generator(), media_type="application/json"))