0
0
FastAPIframework~10 mins

Multiple response types 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 FastAPI and create an app instance.

FastAPI
from fastapi import [1]
app = [1]()
Drag options to blanks, or click blank then click option'
ADepends
BRequest
CResponse
DFastAPI
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Request or Response instead of FastAPI.
Forgetting to call FastAPI() to create the app.
2fill in blank
medium

Complete the code to define a GET endpoint that returns JSON.

FastAPI
@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return [1]
Drag options to blanks, or click blank then click option'
A"Hello"
B{"item_id": item_id}
Citem_id
DNone
Attempts:
3 left
💡 Hint
Common Mistakes
Returning a plain string instead of a dict.
Returning just the integer item_id.
3fill in blank
hard

Fix the error in the response type by completing the code to return a plain text response.

FastAPI
from fastapi.responses import [1]

@app.get("/plaintext")
async def get_plaintext():
    return [1]("Hello World")
Drag options to blanks, or click blank then click option'
APlainTextResponse
BJSONResponse
CHTMLResponse
DRedirectResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Using JSONResponse which returns JSON.
Using HTMLResponse which returns HTML content.
4fill in blank
hard

Fill both blanks to return an HTML response with a custom status code.

FastAPI
from fastapi.responses import [1]

@app.get("/custom_html")
async def custom_html():
    content = "<h1>Welcome</h1>"
    return [1](content=content, status_code=[2])
Drag options to blanks, or click blank then click option'
AHTMLResponse
BPlainTextResponse
C200
D404
Attempts:
3 left
💡 Hint
Common Mistakes
Using PlainTextResponse for HTML content.
Using status code 200 when a custom code is needed.
5fill in blank
hard

Fill all three blanks to return a JSON response with a custom header and status code.

FastAPI
from fastapi.responses import [1]

@app.get("/custom_json")
async def custom_json():
    data = {"message": "Success"}
    headers = [2]
    return [1](content=data, status_code=[3], headers=headers)
Drag options to blanks, or click blank then click option'
AJSONResponse
B{"X-Custom-Header": "Value"}
C201
DPlainTextResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Using PlainTextResponse instead of JSONResponse.
Passing headers as a string instead of a dictionary.