Loading...
Loading...
Compare original and translation side by side
from pydantic import BaseModel, Field, ConfigDict
from typing import Optional
from datetime import datetimefrom pydantic import BaseModel, Field, ConfigDict
from typing import Optional
from datetime import datetimemodel_config = ConfigDict(
str_strip_whitespace=True,
validate_assignment=True,
json_schema_extra={
'example': {
'name': 'Widget',
'price': 29.99,
'quantity': 100,
'description': 'A useful widget'
}
}
)undefinedmodel_config = ConfigDict(
str_strip_whitespace=True,
validate_assignment=True,
json_schema_extra={
'example': {
'name': 'Widget',
'price': 29.99,
'quantity': 100,
'description': 'A useful widget'
}
}
)undefinedfrom fastapi import FastAPI, HTTPException
from pydantic import BaseModel, EmailStr, Field
from typing import List
app = FastAPI()from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, EmailStr, Field
from typing import List
app = FastAPI()undefinedundefinedfrom fastapi import FastAPI, Query
from typing import Optional, List
from enum import Enum
app = FastAPI()from fastapi import FastAPI, Query
from typing import Optional, List
from enum import Enum
app = FastAPI()undefinedundefinedfrom fastapi import FastAPI, Path
from typing import Annotated
app = FastAPI()
@app.get('/users/{user_id}')
async def get_user(
user_id: int = Path(..., gt=0, description='The user ID')
):
return {'user_id': user_id}
@app.get('/items/{item_id}/reviews/{review_id}')
async def get_review(
item_id: Annotated[int, Path(gt=0)],
review_id: Annotated[int, Path(gt=0)]
):
return {'item_id': item_id, 'review_id': review_id}from fastapi import FastAPI, Path
from typing import Annotated
app = FastAPI()
@app.get('/users/{user_id}')
async def get_user(
user_id: int = Path(..., gt=0, description='The user ID')
):
return {'user_id': user_id}
@app.get('/items/{item_id}/reviews/{review_id}')
async def get_review(
item_id: Annotated[int, Path(gt=0)],
review_id: Annotated[int, Path(gt=0)]
):
return {'item_id': item_id, 'review_id': review_id}undefinedundefinedfrom pydantic import BaseModel, field_validator, model_validator
from typing import Any
import re
class UserRegistration(BaseModel):
username: str
email: str
password: str
password_confirm: str
@field_validator('username')
@classmethod
def username_alphanumeric(cls, v: str) -> str:
if not re.match(r'^[a-zA-Z0-9_]+$', v):
raise ValueError('Username must be alphanumeric')
if len(v) < 3:
raise ValueError('Username must be at least 3 characters')
return v.lower()
@field_validator('email')
@classmethod
def validate_email_domain(cls, v: str) -> str:
if not v.endswith(('@example.com', '@example.org')):
raise ValueError('Email must be from example.com or example.org')
return v.lower()
@field_validator('password')
@classmethod
def password_strength(cls, v: str) -> str:
if len(v) < 8:
raise ValueError('Password must be at least 8 characters')
if not re.search(r'[A-Z]', v):
raise ValueError('Password must contain uppercase letter')
if not re.search(r'[a-z]', v):
raise ValueError('Password must contain lowercase letter')
if not re.search(r'[0-9]', v):
raise ValueError('Password must contain digit')
return v
@model_validator(mode='after')
def check_passwords_match(self) -> 'UserRegistration':
if self.password != self.password_confirm:
raise ValueError('Passwords do not match')
return selffrom pydantic import BaseModel, field_validator, model_validator
from typing import Any
import re
class UserRegistration(BaseModel):
username: str
email: str
password: str
password_confirm: str
@field_validator('username')
@classmethod
def username_alphanumeric(cls, v: str) -> str:
if not re.match(r'^[a-zA-Z0-9_]+$', v):
raise ValueError('Username must be alphanumeric')
if len(v) < 3:
raise ValueError('Username must be at least 3 characters')
return v.lower()
@field_validator('email')
@classmethod
def validate_email_domain(cls, v: str) -> str:
if not v.endswith(('@example.com', '@example.org')):
raise ValueError('Email must be from example.com or example.org')
return v.lower()
@field_validator('password')
@classmethod
def password_strength(cls, v: str) -> str:
if len(v) < 8:
raise ValueError('Password must be at least 8 characters')
if not re.search(r'[A-Z]', v):
raise ValueError('Password must contain uppercase letter')
if not re.search(r'[a-z]', v):
raise ValueError('Password must contain lowercase letter')
if not re.search(r'[0-9]', v):
raise ValueError('Password must contain digit')
return v
@model_validator(mode='after')
def check_passwords_match(self) -> 'UserRegistration':
if self.password != self.password_confirm:
raise ValueError('Passwords do not match')
return self@model_validator(mode='after')
def check_dates(self) -> 'DateRange':
if self.start_date >= self.end_date:
raise ValueError('start_date must be before end_date')
return self@model_validator(mode='after')
def check_dates(self) -> 'DateRange':
if self.start_date >= self.end_date:
raise ValueError('start_date must be before end_date')
return self@computed_field
@property
def price_with_tax(self) -> float:
return round(self.price * (1 + self.tax_rate), 2)@computed_field
@property
def price_with_tax(self) -> float:
return round(self.price * (1 + self.tax_rate), 2)@field_validator('name', 'email', mode='before')
@classmethod
def strip_whitespace(cls, v: Any) -> Any:
if isinstance(v, str):
return v.strip()
return vundefined@field_validator('name', 'email', mode='before')
@classmethod
def strip_whitespace(cls, v: Any) -> Any:
if isinstance(v, str):
return v.strip()
return vundefinedfrom pydantic import (
BaseModel,
EmailStr,
HttpUrl,
SecretStr,
conint,
constr,
confloat,
conlist,
UUID4,
IPvAnyAddress,
FilePath,
DirectoryPath,
Json
)
from typing import List
from datetime import date, time
class AdvancedUser(BaseModel):
# String constraints
username: constr(min_length=3, max_length=50, pattern=r'^[a-zA-Z0-9_]+$')
bio: constr(max_length=500) | None = None
# Email and URL
email: EmailStr
website: HttpUrl | None = None
# Numeric constraints
age: conint(ge=13, le=120)
rating: confloat(ge=0.0, le=5.0)
# Secret fields (won't be logged)
password: SecretStr
api_key: SecretStr
# UUID
user_id: UUID4
# Network
ip_address: IPvAnyAddress | None = None
# Date and time
birth_date: date
preferred_time: time | None = None
# Lists with constraints
tags: conlist(str, min_length=1, max_length=10)
# JSON field
metadata: Json | None = Nonefrom pydantic import (
BaseModel,
EmailStr,
HttpUrl,
SecretStr,
conint,
constr,
confloat,
conlist,
UUID4,
IPvAnyAddress,
FilePath,
DirectoryPath,
Json
)
from typing import List
from datetime import date, time
class AdvancedUser(BaseModel):
# String constraints
username: constr(min_length=3, max_length=50, pattern=r'^[a-zA-Z0-9_]+$')
bio: constr(max_length=500) | None = None
# Email and URL
email: EmailStr
website: HttpUrl | None = None
# Numeric constraints
age: conint(ge=13, le=120)
rating: confloat(ge=0.0, le=5.0)
# Secret fields (won't be logged)
password: SecretStr
api_key: SecretStr
# UUID
user_id: UUID4
# Network
ip_address: IPvAnyAddress | None = None
# Date and time
birth_date: date
preferred_time: time | None = None
# Lists with constraints
tags: conlist(str, min_length=1, max_length=10)
# JSON field
metadata: Json | None = Noneundefinedundefinedfrom pydantic import BaseModel
from typing import List, Optionalfrom pydantic import BaseModel
from typing import List, Optionalundefinedundefinedfrom pydantic import BaseModel, ConfigDict, Fieldfrom pydantic import BaseModel, ConfigDict, Fieldid: int # Won't coerce from string
name: strid: int # Won't coerce from string
name: strid: int
name: str
email: strid: int
name: str
email: struser_id: int = Field(alias='userId')
user_name: str = Field(alias='userName')user_id: int = Field(alias='userId')
user_name: str = Field(alias='userName')name: str
# Any extra fields will be storedname: str
# Any extra fields will be storedname: str
# Extra fields will raise validation errorundefinedname: str
# Extra fields will raise validation errorundefinedfrom fastapi import FastAPI
from pydantic import BaseModel
from typing import List
app = FastAPI()
class UserCreate(BaseModel):
username: str
email: EmailStr
password: str
class UserResponse(BaseModel):
id: int
username: str
email: str
# Note: password excluded
model_config = ConfigDict(from_attributes=True)
@app.post('/users', response_model=UserResponse)
async def create_user(user: UserCreate):
# Create user in database
db_user = create_user_in_db(user)
return db_user # Password automatically excludedfrom fastapi import FastAPI
from pydantic import BaseModel
from typing import List
app = FastAPI()
class UserCreate(BaseModel):
username: str
email: EmailStr
password: str
class UserResponse(BaseModel):
id: int
username: str
email: str
# Note: password excluded
model_config = ConfigDict(from_attributes=True)
@app.post('/users', response_model=UserResponse)
async def create_user(user: UserCreate):
# Create user in database
db_user = create_user_in_db(user)
return db_user # Password automatically excludedundefinedundefinedfrom fastapi import FastAPI, HTTPException, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ValidationError
app = FastAPI()from fastapi import FastAPI, HTTPException, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ValidationError
app = FastAPI()return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content={'errors': errors}
)return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content={'errors': errors}
)undefinedundefinedfrom fastapi import FastAPI, File, UploadFile, HTTPException
from typing import List
app = FastAPI()
@app.post('/upload')
async def upload_file(file: UploadFile = File(...)):
# Validate file type
allowed_types = ['image/jpeg', 'image/png', 'image/gif']
if file.content_type not in allowed_types:
raise HTTPException(
status_code=400,
detail=f'File type {file.content_type} not allowed'
)
# Validate file size
contents = await file.read()
max_size = 5 * 1024 * 1024 # 5MB
if len(contents) > max_size:
raise HTTPException(
status_code=400,
detail='File too large (max 5MB)'
)
# Validate filename
if not file.filename.endswith(('.jpg', '.jpeg', '.png', '.gif')):
raise HTTPException(
status_code=400,
detail='Invalid file extension'
)
return {'filename': file.filename, 'size': len(contents)}from fastapi import FastAPI, File, UploadFile, HTTPException
from typing import List
app = FastAPI()
@app.post('/upload')
async def upload_file(file: UploadFile = File(...)):
# Validate file type
allowed_types = ['image/jpeg', 'image/png', 'image/gif']
if file.content_type not in allowed_types:
raise HTTPException(
status_code=400,
detail=f'File type {file.content_type} not allowed'
)
# Validate file size
contents = await file.read()
max_size = 5 * 1024 * 1024 # 5MB
if len(contents) > max_size:
raise HTTPException(
status_code=400,
detail='File too large (max 5MB)'
)
# Validate filename
if not file.filename.endswith(('.jpg', '.jpeg', '.png', '.gif')):
raise HTTPException(
status_code=400,
detail='Invalid file extension'
)
return {'filename': file.filename, 'size': len(contents)}results = []
for file in files:
contents = await file.read()
results.append({
'filename': file.filename,
'size': len(contents)
})
return resultsundefinedresults = []
for file in files:
contents = await file.read()
results.append({
'filename': file.filename,
'size': len(contents)
})
return resultsundefinedfrom fastapi import FastAPI, Form
from pydantic import BaseModel, ValidationError
app = FastAPI()from fastapi import FastAPI, Form
from pydantic import BaseModel, ValidationError
app = FastAPI()undefinedundefinedfrom pydantic import BaseModel, Field, Discriminator
from typing import Literal, Union, Listfrom pydantic import BaseModel, Field, Discriminator
from typing import Literal, Union, Listundefinedundefined