Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to import the correct FastAPI class.
FastAPI
from fastapi import [1] app = [1]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Request or Response instead of FastAPI
Forgetting to instantiate the app
✗ Incorrect
The FastAPI class is used to create the app instance.
2fill in blank
mediumComplete the code to define a Pydantic model for request validation.
FastAPI
from pydantic import BaseModel class User(BaseModel): name: [1] age: int
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using int for name field
Using bool or float for name
✗ Incorrect
The name field should be a string, so use str.
3fill in blank
hardFix the error in the route to accept the User model as request body.
FastAPI
@app.post('/users') async def create_user(user: [1]): return {'name': user.name, 'age': user.age}
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using dict instead of User
Using primitive types like str or int
✗ Incorrect
The route parameter should be the Pydantic model User to validate the request body.
4fill in blank
hardFill both blanks to add a custom validator that checks age is positive.
FastAPI
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
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong field name in the validator
Using the wrong comparison operator
✗ Incorrect
The validator targets the 'age' field and raises an error if the value is less than or equal to 0.
5fill in blank
hardFill all three blanks to create a route that validates a User and returns a greeting.
FastAPI
@app.post('/greet') async def greet_user(user: [1]): return {'message': f'Hello, [2]! You are [3] years old.'}
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using dict instead of User for the parameter
Using wrong variable names in the message
✗ Incorrect
The route accepts a User model, then uses user.name and user.age to create the greeting message.