0
0
FastAPIframework~10 mins

Streaming responses in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the correct class for streaming responses in FastAPI.

FastAPI
from fastapi import FastAPI
from fastapi.responses import [1]

app = FastAPI()
Drag options to blanks, or click blank then click option'
AHTMLResponse
BJSONResponse
CRedirectResponse
DStreamingResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Using JSONResponse or HTMLResponse which are for full responses, not streaming.
Forgetting to import StreamingResponse.
2fill in blank
medium

Complete the code to define a generator function that yields streaming data.

FastAPI
def event_stream():
    for i in range(3):
        yield f"data: Message [1]\n\n"
Drag options to blanks, or click blank then click option'
Ai
Brange
Cevent
Dmessage
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable not defined in the loop.
Forgetting to include the loop variable in the string.
3fill in blank
hard

Fix the error in the FastAPI endpoint to return a streaming response.

FastAPI
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")
Drag options to blanks, or click blank then click option'
AResponse
BStreamingResponse
CJSONResponse
DHTMLResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Returning JSONResponse or Response which do not stream data.
Forgetting to wrap the generator with StreamingResponse.
4fill in blank
hard

Fill both blanks to create a streaming response that streams numbers as bytes.

FastAPI
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")
Drag options to blanks, or click blank then click option'
Aencode
Bdecode
CStreamingResponse
Dformat
Attempts:
3 left
💡 Hint
Common Mistakes
Using decode instead of encode.
Forgetting to convert strings to bytes before streaming.
5fill in blank
hard

Fill all three blanks to create a streaming response with a custom header and chunk size.

FastAPI
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])
Drag options to blanks, or click blank then click option'
A"application/octet-stream"
Bheaders
C1024
D"text/plain"
Attempts:
3 left
💡 Hint
Common Mistakes
Using text/plain for binary data.
Passing headers as a string instead of a dictionary.
Omitting chunk_size or using an invalid value.