What is the purpose of using multiple parameters in the body of a FastAPI endpoint?
It allows you to receive and validate different pieces of data separately in the request body, making your API flexible and clear.
Click to reveal answer
beginner
How do you declare multiple body parameters in a FastAPI endpoint function?
You declare each parameter as a function argument with a Pydantic model or data type, and use Body() to tell FastAPI to expect them in the request body.
Click to reveal answer
intermediate
Why do you need to use Body() explicitly when you have multiple body parameters in FastAPI?
Because FastAPI needs to know which parameters come from the body, and by default it only allows one body parameter without Body(). Using Body() clarifies this.
Click to reveal answer
intermediate
Example: What will happen if you define two Pydantic models as parameters without using Body() in FastAPI?
FastAPI will raise an error because it cannot have more than one body parameter without explicit Body() declarations.
Click to reveal answer
intermediate
How does FastAPI handle validation when multiple body parameters are used?
Each parameter is validated separately according to its Pydantic model or type, so errors are clear and specific to each part of the request body.
Click to reveal answer
In FastAPI, how do you accept two different JSON objects in the request body?
AUse two parameters without Body()
BUse two parameters with Body() in the endpoint function
CPut both objects in a list parameter
DUse query parameters instead
✗ Incorrect
FastAPI requires Body() for each parameter when you have multiple body parameters.
What happens if you omit Body() for multiple body parameters in FastAPI?
AFastAPI accepts it without problems
BFastAPI merges them automatically
CFastAPI treats them as query parameters
DFastAPI raises an error about multiple body parameters
✗ Incorrect
FastAPI does not allow multiple body parameters without explicit Body() usage.
Which of these is a correct way to declare multiple body parameters in FastAPI?
Adef endpoint(a: ModelA, b: ModelB):
Bdef endpoint(a: ModelA = Query(), b: ModelB = Query()):
Cdef endpoint(a: ModelA = Body(), b: ModelB = Body()):
Ddef endpoint(a: ModelA, b: ModelB = Query()):
✗ Incorrect
You must use Body() for each parameter to tell FastAPI they come from the request body.
Why might you want to use multiple body parameters instead of one combined model?
ATo separate concerns and validate parts independently
BTo make the code longer
CTo avoid using Pydantic models
DTo confuse the client
✗ Incorrect
Separating parameters helps keep validation clear and code organized.
If you want to send a JSON object and a list in the body separately, what should you do in FastAPI?
AUse two parameters each with Body()
BUse one parameter with a combined model
CSend one as query parameter
DSend both as strings
✗ Incorrect
Using two parameters with Body() allows FastAPI to parse both separately.
Explain how to define an endpoint in FastAPI that accepts two different JSON objects in the request body.
Think about how FastAPI knows where to get each parameter from.
You got /4 concepts.
Describe why FastAPI requires Body() when you have multiple body parameters and what happens if you omit it.
Consider how FastAPI distinguishes between query, path, and body parameters.
You got /4 concepts.
Practice
(1/5)
1. In FastAPI, how do you accept multiple JSON body parameters in a single endpoint function?
easy
A. Use query parameters instead of body parameters.
B. Use a single parameter with a list of dictionaries.
C. Define multiple function parameters each with a Pydantic model type.
D. Combine all parameters into a single string and parse manually.
Solution
Step 1: Understand FastAPI body parameter handling
FastAPI reads JSON body parameters by matching function argument names and types, typically Pydantic models.
Step 2: Accept multiple parameters
By defining multiple function parameters with Pydantic models, FastAPI expects each as a separate JSON object in the request body.
Final Answer:
Define multiple function parameters each with a Pydantic model type. -> Option C
Quick Check:
Multiple body parameters = multiple Pydantic model arguments [OK]
Hint: Use separate Pydantic models as function parameters for multiple bodies [OK]
Common Mistakes:
Trying to pass multiple JSON objects in one body without models
Using query parameters instead of body for complex data
Combining all data into one string and parsing manually
2. Which of the following is the correct syntax to declare two body parameters user and item in a FastAPI endpoint?
easy
A. async def endpoint(user: User = Body(), item: Item = Body()):
B. async def endpoint(user: User, item: Item = Query()):
C. async def endpoint(user: User, item: Item):
D. async def endpoint(user: User = Query(), item: Item = Body()):
Solution
Step 1: Understand parameter declaration for multiple bodies
FastAPI requires explicit use of Body() for multiple body parameters to distinguish them.
Step 2: Check each option
async def endpoint(user: User = Body(), item: Item = Body()): correctly uses = Body() for both parameters. async def endpoint(user: User, item: Item): misses Body(), so FastAPI treats only the first as body. Options B and D incorrectly mix Query() and Body().
Final Answer:
async def endpoint(user: User = Body(), item: Item = Body()): -> Option A
Quick Check:
Multiple bodies require = Body() [OK]
Hint: Use = Body() for each body parameter to avoid errors [OK]
Common Mistakes:
Omitting = Body() for multiple body parameters
Mixing query and body decorators incorrectly
Using default values without Body()
3. Given the following FastAPI endpoint, what will be the response if the client sends JSON body with {"user": {"name": "Alice"}, "item": {"id": 5}}?
from fastapi import FastAPI, Body
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
name: str
class Item(BaseModel):
id: int
@app.post("/create")
async def create(user: User = Body(), item: Item = Body()):
return {"user_name": user.name, "item_id": item.id}
medium
A. 500 Internal Server Error
B. 422 Unprocessable Entity error
C. {"user": {"name": "Alice"}, "item": {"id": 5}}
D. {"user_name": "Alice", "item_id": 5}
Solution
Step 1: Understand parameter parsing
FastAPI matches the JSON keys "user" and "item" to the parameters user and item respectively, parsing each into the corresponding Pydantic model.
Step 2: Check the return statement
The function returns a dictionary with keys "user_name" and "item_id" extracted from the parsed models, so the response JSON will contain these values.
Final Answer:
{"user_name": "Alice", "item_id": 5} -> Option D
Quick Check:
Parsed models return selected fields as response [OK]
Hint: Response keys come from return dict, not original JSON keys [OK]
Common Mistakes:
Expecting the entire input JSON as output
Confusing 422 error with correct parsing
Assuming server error without code issues
4. Identify the error in this FastAPI endpoint that tries to accept two body parameters user and item:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
name: str
class Item(BaseModel):
id: int
@app.post("/add")
async def add(user: User, item: Item):
return {"user": user, "item": item}
medium
A. Pydantic models cannot be used as parameters.
B. Missing = Body() for multiple body parameters causes validation error.
C. Return statement must convert models to dict before returning.
D. Endpoint must be synchronous, not async.
Solution
Step 1: Check parameter declarations
When multiple body parameters are declared, each must use = Body() to tell FastAPI to parse them from the body separately.
Step 2: Analyze the return statement
Returning Pydantic models directly is allowed; FastAPI serializes them automatically, so no error here.
Final Answer:
Missing = Body() for multiple body parameters causes validation error. -> Option B
Quick Check:
Multiple bodies require = Body() [OK]
Hint: Add = Body() for each body parameter to fix errors [OK]
Common Mistakes:
Omitting = Body() for multiple body parameters
Thinking Pydantic models can't be returned directly
Confusing async with sync function requirements
5. You want to create a FastAPI endpoint that accepts two body parameters: user with fields name and age, and preferences with optional color and food. Which code correctly defines the endpoint and handles missing optional fields gracefully?
hard
A. class User(BaseModel):
name: str
age: int
class Preferences(BaseModel):
color: str | None = None
food: str | None = None
@app.post("/profile")
async def profile(user: User = Body(), preferences: Preferences = Body()):
return {"user": user.dict(), "preferences": preferences.dict()}
B. class User(BaseModel):
name: str
age: int
class Preferences(BaseModel):
color: str
food: str
@app.post("/profile")
async def profile(user: User, preferences: Preferences):
return {"user": user, "preferences": preferences}
C. class User(BaseModel):
name: str
age: int
@app.post("/profile")
async def profile(user: User, preferences: dict = Body()):
return {"user": user, "preferences": preferences}
D. class User(BaseModel):
name: str
age: int
class Preferences(BaseModel):
color: Optional[str]
food: Optional[str]
@app.post("/profile")
async def profile(user: User = Body(), preferences: Preferences = Body()):
return {"user": user.dict(), "preferences": preferences.dict()}
Solution
Step 1: Define optional fields correctly
Using str | None = None sets optional fields with default None, allowing missing keys without error.
Step 2: Declare multiple body parameters with = Body()
This tells FastAPI to parse both user and preferences from the JSON body separately.
Step 3: Return dict representations for JSON serialization
Calling .dict() on Pydantic models converts them to plain dicts for clean JSON output.
Final Answer:
Defines optional fields with `str | None = None`, uses `= Body()` for multiple parameters, and returns `.dict()` representations. -> Option A