Complete the code to declare a request body parameter in 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
In FastAPI, to declare a request body, you define a Pydantic model (here, Item) and use it as the type of the parameter.
Complete the code to import the correct function to declare a request body explicitly.
from fastapi import FastAPI, [1] from pydantic import BaseModel app = FastAPI() class User(BaseModel): username: str email: str @app.post("/users/") async def create_user(user: User = [1]()): return user
The Body function from FastAPI is used to explicitly declare a request body parameter with additional options.
Fix the error in the code to correctly declare a request body with a default value.
from fastapi import FastAPI, Body from pydantic import BaseModel app = FastAPI() class Product(BaseModel): name: str price: float @app.post("/products/") async def create_product(product: Product = [1]): return product
Body(default=None) which makes the body optional.Body() without specifying required or default.Using Body(default=...) tells FastAPI that this parameter is required in the request body.
Fill both blanks to declare a request body with an alias and description.
from fastapi import FastAPI, Body from pydantic import BaseModel app = FastAPI() class Order(BaseModel): item_id: int quantity: int @app.post("/orders/") async def create_order(order: Order = Body([1], description=[2])): return order
Using ... marks the body as required, and description adds helpful info for API docs.
Fill all three blanks to declare a request body with an alias, example, and minimum value validation.
from fastapi import FastAPI, Body from pydantic import BaseModel, Field app = FastAPI() class Payment(BaseModel): amount: float = Field(..., gt=0) method: str @app.post("/payments/") async def create_payment(payment: Payment = Body( ..., alias=[1], example=[2], description=[3] )): return payment
The alias is a string used in the JSON key, example shows sample data, and description explains the parameter.