0
0
FastAPIframework~10 mins

Custom request validation in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
AFastAPI
BRequest
CResponse
DDepends
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Request or Response instead of FastAPI
Forgetting to instantiate the app
2fill in blank
medium

Complete 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'
Aint
Bbool
Cfloat
Dstr
Attempts:
3 left
💡 Hint
Common Mistakes
Using int for name field
Using bool or float for name
3fill in blank
hard

Fix 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'
Adict
BUser
Cstr
Dint
Attempts:
3 left
💡 Hint
Common Mistakes
Using dict instead of User
Using primitive types like str or int
4fill in blank
hard

Fill 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'
Aage
B>
C<=
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong field name in the validator
Using the wrong comparison operator
5fill in blank
hard

Fill 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'
AUser
B{user.name}
C{user.age}
Ddict
Attempts:
3 left
💡 Hint
Common Mistakes
Using dict instead of User for the parameter
Using wrong variable names in the message