0
0
FastAPIframework~10 mins

Why structured responses matter in FastAPI - Test Your Understanding

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

Complete the code to return a JSON response with FastAPI.

FastAPI
from fastapi import FastAPI

app = 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{"item_id": item_id}
Bdict(item_id=item_id)
C[item_id]
Ditem_id
Attempts:
3 left
💡 Hint
Common Mistakes
Returning just the variable without a key
Returning a list instead of a dictionary
2fill in blank
medium

Complete the code to define a Pydantic model for structured response.

FastAPI
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float

@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: int):
    return [1]
Drag options to blanks, or click blank then click option'
AItem(name="Apple", price=1.2)
B{"name": "Apple", "price": 1.2}
Cdict(name="Apple", price=1.2)
D["Apple", 1.2]
Attempts:
3 left
💡 Hint
Common Mistakes
Returning a plain dictionary instead of the model instance
Returning a list instead of an object
3fill in blank
hard

Fix the error in the response to ensure consistent JSON structure.

FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/users/{user_id}")
async def read_user(user_id: int):
    if user_id == 1:
        return {"name": "Alice", "age": 30}
    else:
        return [1]
Drag options to blanks, or click blank then click option'
A["User not found"]
B"User not found"
C{"error": "User not found"}
DNone
Attempts:
3 left
💡 Hint
Common Mistakes
Returning a plain string or list breaks JSON structure
Returning None causes errors
4fill in blank
hard

Fill both blanks to create a consistent response with status code and message.

FastAPI
from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI()

@app.get("/status")
async def get_status():
    return JSONResponse(content=[1], status_code=[2])
Drag options to blanks, or click blank then click option'
A{"status": "ok"}
B200
C404
D{"error": "Not found"}
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string instead of dictionary for content
Using wrong status codes for success
5fill in blank
hard

Fill all three blanks to define a Pydantic model and return it in the response.

FastAPI
from pydantic import BaseModel
from fastapi import FastAPI

app = FastAPI()

class [1](BaseModel):
    title: str
    completed: bool

@app.get("/tasks/{task_id}", response_model=[2])
async def read_task(task_id: int):
    return [3](title="Learn FastAPI", completed=False)
Drag options to blanks, or click blank then click option'
ATask
DItem
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for model and response_model
Returning a dictionary instead of model instance