What is the purpose of declaring a request body in FastAPI?
Declaring a request body in FastAPI tells the framework to expect data sent by the client in the body of the HTTP request, usually in JSON format. This data is then automatically converted into Python objects for easy use.
Click to reveal answer
beginner
How do you declare a request body using Pydantic models in FastAPI?
You create a Pydantic model class with fields representing the expected data, then use it as a function parameter in your path operation. FastAPI reads the request body and converts it into an instance of that model.
Click to reveal answer
intermediate
What happens if the request body does not match the declared Pydantic model in FastAPI?
FastAPI automatically validates the data. If the data is missing required fields or has wrong types, FastAPI returns a clear error response with status code 422 and details about what is wrong.
Click to reveal answer
intermediate
Can you declare multiple request bodies in a single FastAPI endpoint?
No, FastAPI allows only one request body per endpoint. To send multiple pieces of data, you combine them into one Pydantic model or use other parts of the request like query parameters or headers.
Click to reveal answer
intermediate
How do you make a request body field optional in FastAPI?
In the Pydantic model, you use typing.Optional or set a default value for the field. This tells FastAPI that the field is not required in the incoming JSON data.
Click to reveal answer
In FastAPI, how do you tell the framework to expect JSON data in the request body?
ABy declaring a Pydantic model as a parameter in the path operation function
BBy adding a query parameter
CBy setting a header manually
DBy using a cookie
✗ Incorrect
FastAPI uses Pydantic models declared as function parameters to parse and validate JSON request bodies.
What status code does FastAPI return if the request body validation fails?
A400 Bad Request
B422 Unprocessable Entity
C500 Internal Server Error
D404 Not Found
✗ Incorrect
FastAPI returns 422 Unprocessable Entity when the request body data does not match the expected Pydantic model.
Which Python library does FastAPI use to define request body schemas?
ADataclasses
BMarshmallow
CPydantic
DSQLAlchemy
✗ Incorrect
FastAPI uses Pydantic to define data models for request bodies and perform validation.
Can you have two separate request bodies in one FastAPI endpoint?
AYes, by declaring two Pydantic models as parameters
BYes, if you use query parameters
CYes, if you use headers
DNo, only one request body is allowed per endpoint
✗ Incorrect
FastAPI supports only one request body per endpoint. Multiple data pieces should be combined or sent via other request parts.
How do you make a field optional in a FastAPI request body model?
AUse typing.Optional or provide a default value in the Pydantic model
BLeave the field out of the model
CSet the field to None in the request
DUse a query parameter instead
✗ Incorrect
Using typing.Optional or default values in Pydantic models makes fields optional in FastAPI request bodies.
Explain how to declare and use a request body in FastAPI using Pydantic models.
Think about how you tell FastAPI what data to expect and how it checks it.
You got /4 concepts.
Describe what happens when the incoming request body does not match the declared Pydantic model in FastAPI.
Consider how FastAPI helps keep your app safe from bad data.
You got /4 concepts.
Practice
(1/5)
1. What is the main purpose of declaring a request body in FastAPI using a Pydantic model?
easy
A. To define the URL path for the API endpoint
B. To tell FastAPI what data structure to expect and validate from the client
C. To specify the HTTP method like GET or POST
D. To set the response status code
Solution
Step 1: Understand request body role
The request body contains data sent by the client to the server, usually in POST or PUT requests.
Step 2: Role of Pydantic model in FastAPI
Using a Pydantic model tells FastAPI the expected data shape and automatically validates it.
Final Answer:
To tell FastAPI what data structure to expect and validate from the client -> Option B
Quick Check:
Request body declaration = Data validation [OK]
Hint: Request body = data shape + validation [OK]
Common Mistakes:
Confusing request body with URL path
Thinking request body sets HTTP method
Assuming request body controls response code
2. Which of the following is the correct way to declare a request body parameter in a FastAPI endpoint?
easy
A. def create_item(item: dict):
B. def create_item(item: BaseModel):
C. def create_item(item: Item):
D. def create_item(item: str):
Solution
Step 1: Recognize Pydantic model usage
FastAPI expects a Pydantic model class (like Item) to declare request body parameters.
Step 2: Check each option
def create_item(item: dict): uses dict which works but is not recommended; def create_item(item: BaseModel): uses BaseModel directly which is abstract; def create_item(item: Item): uses a user-defined model Item which is correct; def create_item(item: str): uses str which is not a model.
Final Answer:
def create_item(item: Item): -> Option C
Quick Check:
Use Pydantic model class for request body [OK]
Hint: Use your Pydantic model class as parameter type [OK]
Common Mistakes:
Using dict instead of a Pydantic model
Using BaseModel directly instead of subclass
Using primitive types like str for complex data
3. Given this FastAPI code snippet, what will be the output if the client sends JSON {"name": "apple", "price": 5}?
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: Item):
return {"item_name": item.name, "item_price": item.price}
medium
A. {"item_name": "apple", "item_price": "5"}
B. 500 Internal Server Error
C. ValidationError because price is int, not float
D. {"item_name": "apple", "item_price": 5.0}
Solution
Step 1: Understand Pydantic type conversion
Pydantic automatically converts compatible types, so int 5 converts to float 5.0.
Step 2: Check returned dictionary
The function returns a dict with keys "item_name" and "item_price" using the values from the item object.
Final Answer:
{"item_name": "apple", "item_price": 5.0} -> Option D
Quick Check:
Int converts to float automatically in Pydantic [OK]
Hint: Pydantic converts int to float automatically [OK]
Common Mistakes:
Thinking int and float types cause validation error
Expecting string instead of float for price
Assuming server error on type mismatch
4. Identify the error in this FastAPI endpoint declaration:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
username: str
age: int
@app.post("/users/")
def create_user(user: User = None):
return {"username": user.username, "age": user.age}
medium
A. Request body parameter cannot have a default value None
B. Missing async keyword in endpoint function
C. User class must inherit from object, not BaseModel
D. Return statement must be inside an async function
Solution
Step 1: Check request body parameter declaration
In FastAPI, request body parameters cannot have a default value of None because the body is required by default.
Step 2: Review other options
Async is optional for FastAPI endpoints; BaseModel inheritance is correct; return works in sync functions.
Final Answer:
Request body parameter cannot have a default value None -> Option A
Quick Check:
Request body params must not default to None [OK]
Hint: Request body params must be required unless explicitly optional [OK]
Common Mistakes:
Adding default None to request body param
Thinking async is mandatory
Misunderstanding BaseModel inheritance
5. You want to declare a request body in FastAPI that accepts an optional field description which can be missing or null. How should you declare the Pydantic model to handle this correctly?
hard
A. from pydantic import BaseModel
from typing import Optional
class Item(BaseModel):
name: str
description: Optional[str] = None
B. from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str
C. from pydantic import BaseModel
from typing import Union
class Item(BaseModel):
name: str
description: Union[str, None] = None
D. from pydantic import BaseModel
class Item(BaseModel):
name: str
description: None
Solution
Step 1: Understand optional fields in Pydantic
To allow a field to be optional or null, use Optional[type] with a default value None.
Step 2: Analyze each option
from pydantic import BaseModel
from typing import Optional
class Item(BaseModel):
name: str
description: Optional[str] = None correctly uses Optional[str] with default None; from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str requires description always; from pydantic import BaseModel
from typing import Union
class Item(BaseModel):
name: str
description: Union[str, None] = None uses Union[str, None] with default None; from pydantic import BaseModel
class Item(BaseModel):
name: str
description: None sets description to None type which is invalid.
Final Answer:
Use Optional[str] with default None for optional nullable field -> Option A
Quick Check:
Optional field = Optional[type] + default None [OK]
Hint: Use Optional[type] and default None for optional fields [OK]
Common Mistakes:
Forgetting to set default None for optional fields
Using plain type without Optional for nullable fields
Assigning None as a type instead of a value
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.