Complete the code to import the correct class for streaming responses in FastAPI.
from fastapi import FastAPI from fastapi.responses import [1] app = FastAPI()
The StreamingResponse class is used in FastAPI to send streaming data as a response.
Complete the code to define a generator function that yields streaming data.
def event_stream(): for i in range(3): yield f"data: Message [1]\n\n"
The variable i is used in the loop and should be included in the yielded string.
Fix the error in the FastAPI endpoint to return a streaming response.
from fastapi import FastAPI from fastapi.responses import StreamingResponse app = FastAPI() def generate(): yield "Hello\n" @app.get("/stream") async def stream(): return [1](generate(), media_type="text/plain")
The endpoint must return a StreamingResponse to stream data properly.
Fill both blanks to create a streaming response that streams numbers as bytes.
def number_stream(): for num in range(1, 4): yield str(num).[1]() @app.get("/numbers") async def numbers(): return [2](number_stream(), media_type="application/octet-stream")
The numbers must be converted to bytes by calling encode(). The streaming response class is StreamingResponse.
Fill all three blanks to create a streaming response with a custom header and chunk size.
from fastapi.responses import StreamingResponse async def custom_stream(): yield b"chunk1" yield b"chunk2" @app.get("/custom") async def custom(): headers = {"X-Custom-Header": "Value"} return StreamingResponse(custom_stream(), media_type=[1], headers=[2], chunk_size=[3])
The media type for binary data is application/octet-stream. The headers dictionary must be passed as is. The chunk size is set to 1024 bytes for streaming.