0
0
FastAPIframework~20 mins

Custom request validation in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
FastAPI Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output when a FastAPI endpoint uses a custom validator that raises a ValueError?

Consider this FastAPI endpoint with a Pydantic model that has a custom validator raising ValueError if a condition fails. What will the client receive if the validation fails?

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel, validator

app = FastAPI()

class Item(BaseModel):
    name: str
    quantity: int

    @validator('quantity')
    def quantity_must_be_positive(cls, v):
        if v <= 0:
            raise ValueError('Quantity must be positive')
        return v

@app.post('/items/')
async def create_item(item: Item):
    return item
AThe client receives a 422 Unprocessable Entity response with a JSON error explaining 'Quantity must be positive'.
BThe server crashes with a ValueError and no response is sent to the client.
CThe client receives a 500 Internal Server Error with no details.
DThe client receives a 200 OK response with the invalid data echoed back.
Attempts:
2 left
💡 Hint

Think about how FastAPI handles validation errors raised by Pydantic.

📝 Syntax
intermediate
2:00remaining
Which code snippet correctly implements a custom request validator in FastAPI using Pydantic?

Choose the code that correctly defines a Pydantic model with a custom validator for a field age that must be at least 18.

A
class User(BaseModel):
    age: int

    @validator('age')
    def check_age(cls, v):
        if v &lt; 18:
            raise ValueError('Must be at least 18')
        return v
B
class User(BaseModel):
    age: int

    def check_age(self):
        if self.age &lt; 18:
            raise ValueError('Must be at least 18')
C
class User(BaseModel):
    age: int

    @validate('age')
    def check_age(cls, v):
        if v &lt; 18:
            raise ValueError('Must be at least 18')
        return v
D
class User(BaseModel):
    age: int

    @validator
    def check_age(cls, v):
        if v &lt; 18:
            raise ValueError('Must be at least 18')
        return v
Attempts:
2 left
💡 Hint

Remember the correct decorator name and its usage in Pydantic.

🔧 Debug
advanced
2:00remaining
Why does this FastAPI custom validator not run and how to fix it?

Given this Pydantic model, the custom validator does not seem to run when the API receives data. What is the cause?

FastAPI
from pydantic import BaseModel, validator

class Product(BaseModel):
    price: float

    def validate_price(cls, v):
        if v <= 0:
            raise ValueError('Price must be positive')
        return v
AThe validator must be a static method, so it needs <code>@staticmethod</code> decorator.
BThe method should be named <code>check_price</code> instead of <code>validate_price</code>.
CThe method is missing the <code>@validator('price')</code> decorator, so it is never called.
DThe validator must return a boolean, not the value.
Attempts:
2 left
💡 Hint

Check how Pydantic knows which methods are validators.

state_output
advanced
2:00remaining
What is the response when a FastAPI endpoint uses a root validator that modifies data?

Given this Pydantic model with a root validator that changes the full_name field, what will the API return when posting {"first_name": "Jane", "last_name": "Doe"}?

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel, root_validator

app = FastAPI()

class User(BaseModel):
    first_name: str
    last_name: str
    full_name: str = ''

    @root_validator
    def set_full_name(cls, values):
        values['full_name'] = f"{values.get('first_name', '')} {values.get('last_name', '')}"
        return values

@app.post('/users/')
async def create_user(user: User):
    return user.dict()
A{"first_name": "Jane", "last_name": "Doe", "full_name": ""}
B422 Unprocessable Entity error because full_name is empty by default
C500 Internal Server Error due to root_validator modifying values
D{"first_name": "Jane", "last_name": "Doe", "full_name": "Jane Doe"}
Attempts:
2 left
💡 Hint

Think about what a root validator can do to the data before returning it.

🧠 Conceptual
expert
2:00remaining
Which statement best describes how FastAPI handles custom request validation errors?

Choose the statement that correctly explains FastAPI's behavior when a custom validation error occurs in a Pydantic model used for request validation.

AFastAPI ignores validation errors raised by Pydantic and passes the invalid data to the endpoint function.
BFastAPI catches validation errors raised by Pydantic validators and automatically returns a 422 response with detailed error messages in JSON format.
CFastAPI converts all validation errors into 500 Internal Server Errors without details to avoid leaking information.
DFastAPI requires manual try-except blocks in each endpoint to catch validation errors and return responses.
Attempts:
2 left
💡 Hint

Recall how FastAPI integrates with Pydantic for validation.