0
0
FastAPIframework~10 mins

Response model declaration 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 declare a response model in FastAPI.

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

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

@app.get("/items/{item_id}", response_model=[1])
def read_item(item_id: int):
    return {"name": "Foo", "price": 42.0}
Drag options to blanks, or click blank then click option'
Aint
BItem
Cstr
Dfloat
Attempts:
3 left
💡 Hint
Common Mistakes
Using basic types like int or str instead of a Pydantic model.
Forgetting to import or define the model.
2fill in blank
medium

Complete the code to specify a response model for a POST endpoint.

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    username: str
    email: str

@app.post("/users/", response_model=[1])
def create_user(user: User):
    return user
Drag options to blanks, or click blank then click option'
Adict
Bstr
Clist
DUser
Attempts:
3 left
💡 Hint
Common Mistakes
Using basic types like dict or list instead of the Pydantic model.
Not matching the response_model to the returned data.
3fill in blank
hard

Fix the error in the response model declaration.

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Product(BaseModel):
    id: int
    name: str

@app.get("/products/{product_id}", response_model=[1])
def get_product(product_id: int):
    return {"id": product_id, "name": "Gadget"}
Drag options to blanks, or click blank then click option'
AProduct
Bdict
Cint
Dstr
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'dict' or primitive types as response_model.
Mismatch between response_model and returned data structure.
4fill in blank
hard

Fill both blanks to declare a response model and import the needed class.

FastAPI
from fastapi import FastAPI
from pydantic import [1]

app = FastAPI()

class Order([2]):
    order_id: int
    item: str
Drag options to blanks, or click blank then click option'
ABaseModel
BFastAPI
CRequest
DResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Importing or inheriting from FastAPI or other unrelated classes.
Forgetting to import BaseModel.
5fill in blank
hard

Fill all three blanks to declare a response model, import BaseModel, and use it as base class.

FastAPI
from fastapi import FastAPI
from pydantic import [1]

app = FastAPI()

class Customer([2]):
    id: int
    name: str

@app.get("/customers/{customer_id}", response_model=[3])
def get_customer(customer_id: int):
    return {"id": customer_id, "name": "Alice"}
Drag options to blanks, or click blank then click option'
ABaseModel
BFastAPI
CCustomer
DRequest
Attempts:
3 left
💡 Hint
Common Mistakes
Using FastAPI or Request instead of BaseModel.
Using wrong response_model name.