Bird
Raised Fist0
FastAPIframework~20 mins

Streaming responses in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Streaming Response Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What does this FastAPI streaming response output?
Consider this FastAPI endpoint that streams numbers as text lines. What will the client receive when calling this endpoint?
FastAPI
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import asyncio

app = FastAPI()

async def number_stream():
    for i in range(3):
        yield f"Number: {i}\n"
        await asyncio.sleep(0.1)

@app.get("/numbers")
async def stream_numbers():
    return StreamingResponse(number_stream(), media_type="text/plain")
AThe client receives a JSON array ["Number: 0", "Number: 1", "Number: 2"] all at once.
BThe client receives a streamed response with lines: 'Number: 0', 'Number: 1', 'Number: 2' each followed by a newline, arriving with small delays.
CThe client receives a single string 'Number: 0Number: 1Number: 2' without newlines or delays.
DThe client receives an error because StreamingResponse cannot stream async generators.
Attempts:
2 left
💡 Hint
Think about what StreamingResponse does with an async generator and the media type.
📝 Syntax
intermediate
2:00remaining
Which option correctly creates a streaming response from a synchronous generator?
You want to stream data from a synchronous generator function in FastAPI. Which code snippet correctly wraps it for StreamingResponse?
FastAPI
def sync_generator():
    for i in range(3):
        yield f"data {i}\n"
Areturn StreamingResponse(sync_generator(), media_type="text/plain")
Breturn StreamingResponse(iter(sync_generator()), media_type="text/plain")
Creturn StreamingResponse(async_generator(sync_generator()), media_type="text/plain")
Dreturn StreamingResponse(sync_generator, media_type="text/plain")
Attempts:
2 left
💡 Hint
StreamingResponse accepts any iterable or async iterable as first argument.
🔧 Debug
advanced
2:00remaining
Why does this FastAPI streaming endpoint raise a RuntimeError?
Examine this code snippet. Why does it raise 'RuntimeError: async generator ignored' when called?
FastAPI
from fastapi import FastAPI
from fastapi.responses import StreamingResponse

app = FastAPI()

def sync_gen():
    yield "hello\n"

@app.get("/stream")
async def stream():
    return StreamingResponse(sync_gen(), media_type="text/plain")
ABecause the sync generator yields strings instead of bytes.
BBecause StreamingResponse expects an async generator but got a sync generator in an async endpoint.
CBecause the endpoint is async but returns a sync generator without wrapping it in an async iterator.
DBecause StreamingResponse requires the media_type to be 'application/octet-stream' for generators.
Attempts:
2 left
💡 Hint
Think about how async endpoints handle sync generators in StreamingResponse.
❓ state_output
advanced
2:00remaining
What is the output of this FastAPI streaming response with stateful generator?
Given this code, what will the client receive when calling /count?
FastAPI
from fastapi import FastAPI
from fastapi.responses import StreamingResponse

app = FastAPI()

class Counter:
    def __init__(self):
        self.count = 0
    def __iter__(self):
        return self
    def __next__(self):
        if self.count >= 3:
            raise StopIteration
        self.count += 1
        return f"Count: {self.count}\n"

@app.get("/count")
def count_stream():
    counter = Counter()
    return StreamingResponse(counter, media_type="text/plain")
AThe client receives streamed lines: 'Count: 1', 'Count: 2', 'Count: 3' each followed by newline.
BThe client receives a JSON array ["Count: 1", "Count: 2", "Count: 3"] all at once.
CThe client receives a single string 'Count: 123' without newlines or streaming.
DThe client receives an error because Counter is not an async iterable.
Attempts:
2 left
💡 Hint
StreamingResponse can stream from any iterable, including stateful ones.
🧠 Conceptual
expert
2:00remaining
Which statement about FastAPI StreamingResponse and async generators is TRUE?
Select the correct statement about using StreamingResponse with async generators in FastAPI.
AStreamingResponse can only stream synchronous generators; async generators cause runtime errors.
BStreamingResponse automatically converts synchronous generators to async generators internally.
CStreamingResponse requires the async generator to be fully consumed before sending any data to the client.
DStreamingResponse can stream async generators, but the endpoint must be async and return the StreamingResponse directly without awaiting the generator.
Attempts:
2 left
💡 Hint
Consider how async generators and StreamingResponse interact in async endpoints.

Practice

(1/5)
1. What is the main benefit of using StreamingResponse in FastAPI?
easy
A. It compresses the entire response into a single file.
B. It automatically caches all responses for faster access.
C. It converts JSON data into XML format before sending.
D. It sends data in small parts instead of all at once, improving efficiency.

Solution

  1. Step 1: Understand what streaming means

    Streaming sends data in chunks, not all at once, which helps with large data or slow connections.
  2. Step 2: Identify the role of StreamingResponse

    FastAPI's StreamingResponse helps send these chunks efficiently to the client.
  3. Final Answer:

    It sends data in small parts instead of all at once, improving efficiency. -> Option D
  4. Quick Check:

    Streaming = sending data in parts [OK]
Hint: Streaming sends data bit by bit, not all at once [OK]
Common Mistakes:
  • Thinking StreamingResponse caches data
  • Confusing streaming with data compression
  • Assuming it changes data format automatically
2. Which of the following is the correct way to import StreamingResponse in FastAPI?
easy
A. from fastapi import StreamingResponse
B. import StreamingResponse from fastapi.responses
C. from fastapi.responses import StreamingResponse
D. import StreamingResponse as sr from fastapi

Solution

  1. Step 1: Recall FastAPI import syntax

    FastAPI uses standard Python import syntax: from module import class/function.
  2. Step 2: Identify correct module for StreamingResponse

    StreamingResponse is in fastapi.responses, so correct import is from fastapi.responses import StreamingResponse.
  3. Final Answer:

    from fastapi.responses import StreamingResponse -> Option C
  4. Quick Check:

    Correct import = from fastapi.responses import StreamingResponse [OK]
Hint: Use 'from fastapi.responses import StreamingResponse' [OK]
Common Mistakes:
  • Using incorrect import syntax like 'import StreamingResponse from ...'
  • Importing directly from 'fastapi' instead of 'fastapi.responses'
  • Trying to alias import incorrectly
3. Given this FastAPI endpoint code, what will the client receive?
from fastapi import FastAPI
from fastapi.responses import StreamingResponse

app = FastAPI()

def generate_numbers():
    for i in range(3):
        yield f"Number: {i}\n"

@app.get("/numbers")
def numbers():
    return StreamingResponse(generate_numbers(), media_type="text/plain")
medium
A. A streamed response sending 'Number: 0\n', then 'Number: 1\n', then 'Number: 2\n' in parts
B. A single response with 'Number: 0\nNumber: 1\nNumber: 2\n' all at once
C. Three separate responses, each with one number
D. An error because StreamingResponse cannot use generators

Solution

  1. Step 1: Understand the generator function

    The function generate_numbers yields strings one by one for i in 0 to 2.
  2. Step 2: Analyze StreamingResponse behavior

    StreamingResponse sends data chunks as they are yielded, so client receives parts streamed.
  3. Final Answer:

    A streamed response sending 'Number: 0\n', then 'Number: 1\n', then 'Number: 2\n' in parts -> Option A
  4. Quick Check:

    Generator + StreamingResponse = streamed chunks [OK]
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

  1. Step 1: Check stream_data function logic

    Inside the loop, return exits the function immediately, so only first item 'a' is returned.
  2. Step 2: Understand streaming requires yield

    StreamingResponse expects an iterable or generator; yield produces chunks one by one.
  3. Final Answer:

    The function stream_data uses return inside the loop instead of yield. -> Option A
  4. 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

  1. Step 1: Understand streaming large files

    Reading line by line with a generator avoids loading whole file into memory.
  2. Step 2: Match StreamingResponse usage

    StreamingResponse accepts an iterable like a generator that yields file lines.
  3. 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.
  4. Final Answer:

    Use a generator that opens the file and yields each line, then return StreamingResponse with that generator. -> Option B
  5. Quick Check:

    Generator + StreamingResponse = efficient file streaming [OK]
Hint: Stream files by yielding lines in a generator [OK]
Common Mistakes:
  • Loading entire file into memory before streaming
  • Passing file path string instead of iterable
  • Returning file size instead of content
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard