Performance: String validation (min, max, regex)
This affects the server response time and user experience by validating input strings before processing.
from fastapi import FastAPI from pydantic import BaseModel, Field app = FastAPI() class UserInput(BaseModel): username: str = Field(min_length=3, max_length=20, regex=r'^[a-zA-Z0-9_]+$') @app.post('/submit') async def submit(data: UserInput): return {'message': 'Success'}
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class UserInput(BaseModel): username: str @app.post('/submit') async def submit(data: UserInput): if len(data.username) < 3 or len(data.username) > 20: return {'error': 'Username length invalid'} import re if not re.match(r'^[a-zA-Z0-9_]+$', data.username): return {'error': 'Username pattern invalid'} return {'message': 'Success'}
| Pattern | Server Processing | Validation Calls | Response Delay | Verdict |
|---|---|---|---|---|
| Manual validation in endpoint | High (multiple checks) | Multiple per request | Increases by several ms | [X] Bad |
| Pydantic constr validation | Low (single validation) | Once per request | Minimal delay | [OK] Good |
constr function in FastAPI's Pydantic models help you do?constr purposeconstr is a Pydantic type used to validate string fields with constraints like length and regex.constr usage for string validation.min_length and max_length inside constr().constr(min_length=3, max_length=10) correctly. Options A, B, and D use wrong parameter names or types.from pydantic import BaseModel, constr
class User(BaseModel):
username: constr(min_length=4, max_length=8, regex=r'^[a-zA-Z]+$')User(username='abc123')?r'^[a-zA-Z]+$' allows only letters, no digits.from pydantic import BaseModel, constr
class Item(BaseModel):
code: constr(min_length=5, max=10)max_length, not max.max=10 causes a syntax or validation error because it's invalid.password that must be between 8 and 16 characters and include at least one digit. Which is the correct way to define it?min_length=8 and max_length=16 in constr for length limits.r'^(?=.*\\d).+$' ensures at least one digit is present.min and max. password: str(min_length=8, max_length=16, regex=r'^(?=.*\\d).+$') wrongly applies regex to str type.Pass the test and this pattern moves unknown