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?
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
Think about how FastAPI handles validation errors raised by Pydantic.
FastAPI uses Pydantic for validation. When a validator raises ValueError, FastAPI catches it and returns a 422 response with details about the validation error.
Choose the code that correctly defines a Pydantic model with a custom validator for a field age that must be at least 18.
Remember the correct decorator name and its usage in Pydantic.
The @validator decorator requires the field name as a string argument. Option A correctly uses @validator('age'). Option A uses a wrong decorator name, B is missing the decorator, and A misses the field name argument.
Given this Pydantic model, the custom validator does not seem to run when the API receives data. What is the cause?
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
Check how Pydantic knows which methods are validators.
In Pydantic, validators must be decorated with @validator('field_name') to be recognized and run. Without the decorator, the method is just a normal method and not called during validation.
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"}?
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()
Think about what a root validator can do to the data before returning it.
The root validator runs after individual field validation and can modify the entire data dictionary. Here it sets full_name by combining first and last names. The API returns the updated data including the computed full_name.
Choose the statement that correctly explains FastAPI's behavior when a custom validation error occurs in a Pydantic model used for request validation.
Recall how FastAPI integrates with Pydantic for validation.
FastAPI automatically handles Pydantic validation errors by returning a 422 status code with a JSON body describing the errors. This behavior is built-in and requires no manual error handling in endpoints.