0
0
FastAPIframework~10 mins

Why request bodies carry structured data 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 define a POST endpoint that accepts a JSON body.

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

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

@app.post("/items/")
async def create_item(item: [1]):
    return item
Drag options to blanks, or click blank then click option'
AItem
Bstr
Cint
Ddict
Attempts:
3 left
💡 Hint
Common Mistakes
Using primitive types like str or int instead of the Pydantic model.
Forgetting to define a Pydantic model for structured data.
2fill in blank
medium

Complete the code to access the 'name' field from the request body model.

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    username: str
    age: int

@app.post("/users/")
async def create_user(user: User):
    return {"username": user.[1]
Drag options to blanks, or click blank then click option'
Aage
Bid
Cname
Dusername
Attempts:
3 left
💡 Hint
Common Mistakes
Using a field name not defined in the model like 'name' or 'id'.
Trying to access the whole object instead of a specific field.
3fill in blank
hard

Fix the error in the code by completing the parameter type to accept structured JSON data.

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Product(BaseModel):
    title: str
    quantity: int

@app.post("/products/")
async def add_product(product: [1]):
    return product
Drag options to blanks, or click blank then click option'
AProduct
Bdict
Clist
Dstr
Attempts:
3 left
💡 Hint
Common Mistakes
Using dict or str instead of the Pydantic model.
Not importing or defining the model class.
4fill in blank
hard

Fill both blanks to create a Pydantic model with fields 'email' and 'is_active'.

FastAPI
from pydantic import BaseModel

class UserStatus(BaseModel):
    email: [1]
    is_active: [2]
Drag options to blanks, or click blank then click option'
Astr
Bint
Cbool
Dfloat
Attempts:
3 left
💡 Hint
Common Mistakes
Using int or float for email or is_active fields.
Mixing up data types for these fields.
5fill in blank
hard

Fill all three blanks to define a POST endpoint that accepts a structured request body and returns a dictionary with the user's name and age.

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Person(BaseModel):
    name: [1]
    age: [2]

@app.post("/persons/")
async def create_person(person: [3]):
    return {"name": person.name, "age": person.age}
Drag options to blanks, or click blank then click option'
Astr
Bint
CPerson
Dfloat
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong data types for fields.
Not using the model class as the parameter type.