from fastapi import FastAPI from pydantic import BaseModel, Field app = FastAPI() class User(BaseModel): name: str = Field(min_length=3, max_length=10) age: int = Field(gt=18, lt=30) @app.post("/user") async def create_user(user: User): return {"message": f"User {user.name} aged {user.age} created"}
The name "Anna" has length 4, which is between 3 and 10. The age 25 is greater than 18 and less than 30. So the input passes validation and the endpoint returns the success message.
The correct parameters for string length constraints are min_length and max_length. Other options use invalid parameter names.
from pydantic import BaseModel, Field class Result(BaseModel): score: int = Field(ge=0, le=100)
The parameters ge=0 and le=100 mean the value must be between 0 and 100 inclusive. 101 is outside this range, so validation fails.
from pydantic import BaseModel, Field class User(BaseModel): username: str = Field(min_length=3, max_length=8) active: bool = Field(default=True) input_data = {"username": "bob"} user = User(**input_data)
The 'active' field has a default value of True, so if not provided, it will be set to True automatically.
Field constraints are enforced by Pydantic during runtime validation of incoming data, rejecting invalid inputs with errors.
