Complete the code to return a JSON response with FastAPI.
from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): return [1]
FastAPI expects a dictionary or Pydantic model to return structured JSON responses.
Complete the code to define a Pydantic model for structured response.
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]
Returning an instance of the Pydantic model ensures the response matches the declared schema.
Fix the error in the response to ensure consistent JSON structure.
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]
Returning a dictionary with an error key keeps the response structure consistent.
Fill both blanks to create a consistent response with status code and message.
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])
Use a dictionary for content and a valid HTTP status code for status_code.
Fill all three blanks to define a Pydantic model and return it in the response.
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)
Define a model named Task and use it as the response_model and return its instance.