Hint: Generators yield chunks; StreamingResponse streams them [OK]
Common Mistakes:
Thinking all data sends at once
Expecting multiple separate HTTP responses
Assuming StreamingResponse rejects generators
4. Identify the error in this FastAPI streaming endpoint code:
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
def stream_data():
data = ["a", "b", "c"]
for d in data:
return d
@app.get("/stream")
def stream():
return StreamingResponse(stream_data(), media_type="text/plain")
medium
A. The function stream_data uses return inside the loop instead of yield.
B. StreamingResponse requires media_type to be 'application/json'.
C. The endpoint path should be '/stream_data' not '/stream'.
D. FastAPI does not support StreamingResponse with string data.
Solution
Step 1: Check stream_data function logic
Inside the loop, return exits the function immediately, so only first item 'a' is returned.
Step 2: Understand streaming requires yield
StreamingResponse expects an iterable or generator; yield produces chunks one by one.
Final Answer:
The function stream_data uses return inside the loop instead of yield. -> Option A
Quick Check:
Use yield, not return, for streaming generators [OK]
Hint: Use yield inside loops for streaming, not return [OK]
Common Mistakes:
Using return inside generator loops
Wrong media_type for StreamingResponse
Confusing endpoint path naming
Believing StreamingResponse can't stream strings
5. You want to stream a large CSV file line by line using FastAPI. Which approach correctly combines streaming with file reading?
hard
A. Use StreamingResponse with a function that returns the file size.
B. Use a generator that opens the file and yields each line, then return StreamingResponse with that generator.
C. Return StreamingResponse with the file path string directly.
D. Read the entire file into memory, then return StreamingResponse with a list of lines.
Solution
Step 1: Understand streaming large files
Reading line by line with a generator avoids loading whole file into memory.
Step 2: Match StreamingResponse usage
StreamingResponse accepts an iterable like a generator that yields file lines.
Step 3: Evaluate options
Use a generator that opens the file and yields each line, then return StreamingResponse with that generator. This uses a generator to yield lines, which is efficient and correct. Others either load all data or misuse StreamingResponse.
Final Answer:
Use a generator that opens the file and yields each line, then return StreamingResponse with that generator. -> Option B