Complete the code to import the correct FastAPI class.
from fastapi import [1] app = [1]()
The FastAPI class is used to create the app instance.
Complete the code to define a Pydantic model for request validation.
from pydantic import BaseModel class User(BaseModel): name: [1] age: int
The name field should be a string, so use str.
Fix the error in the route to accept the User model as request body.
@app.post('/users') async def create_user(user: [1]): return {'name': user.name, 'age': user.age}
The route parameter should be the Pydantic model User to validate the request body.
Fill both blanks to add a custom validator that checks age is positive.
from pydantic import BaseModel, field_validator class User(BaseModel): name: str age: int @field_validator('[1]') def check_age(cls, value): if value [2] 0: raise ValueError('Age must be positive') return value
The validator targets the 'age' field and raises an error if the value is less than or equal to 0.
Fill all three blanks to create a route that validates a User and returns a greeting.
@app.post('/greet') async def greet_user(user: [1]): return {'message': f'Hello, [2]! You are [3] years old.'}
The route accepts a User model, then uses user.name and user.age to create the greeting message.
