Validation in FastApi
Sivak Ihor
Posted on July 22, 2024
Introduction
FastAPI is a modern web framework for building APIs with Python. One of its most important and convenient features is the built-in support for data validation using Pydantic. Validators in FastAPI help ensure that the data transmitted through the API meets the specified requirements, improving the security and reliability of applications.
Basics of Validation
Using Pydantic
FastAPI integrates with the Pydantic library for data validation. Pydantic allows you to define data models with clear types and validation rules. This makes it easy to check that user-provided data meets expected formats.
Key Features of Pydantic:
Data Typing:
Models in Pydantic are defined as subclasses of BaseModel, where fields are described using Python types.
from pydantic import BaseModel
class User(BaseModel):
username: str
email: str
Types in Pydantic
Pydantic supports a wide range of data types for validation and serialization. Here is a comprehensive list of the types you can use when defining models:
1. Basic Data Types:
int: Integer
from pydantic import BaseModel
class Item(BaseModel):
quantity: int
float: Floating-point number
from pydantic import BaseModel
class Product(BaseModel):
price: float
str: String
from pydantic import BaseModel
class User(BaseModel):
username: str
bool: Boolean value (True or False)
from pydantic import BaseModel
class Settings(BaseModel):
is_active: bool
2. Optional:
Optional[X]: Value can be of type X or None. Equivalent to Union[X, None].
from typing import Optional
from pydantic import BaseModel
class User(BaseModel):
age: Optional[int] # Can be int or None
3. Union:
Union[X, Y]: Value can be one of several types (X or Y).
from typing import Union
from pydantic import BaseModel
class Item(BaseModel):
model: Union[str, int]
4. Literal:
Literal[value1, value2, ...]: Value must be one of the specified literal values.
from typing import Literal
from pydantic import BaseModel
class Car(BaseModel):
type: Literal['sedan', 'suv', 'truck']
5. Constrained Types:
conint(gt=0): Integer that must be greater than 0.
from pydantic import BaseModel, conint
class Order(BaseModel):
quantity: conint(gt=0) # Only positive numbers
confloat(ge=0.0, le=100.0): Floating-point number that must be within the range of 0.0 to 100.0.
from pydantic import BaseModel, confloat
class Measurement(BaseModel):
value: confloat(ge=0.0, le=100.0) # Value between 0 and 100
constr(min_length=5, max_length=20): String whose length must be between 5 and 20 characters.
from pydantic import BaseModel, constr
class User(BaseModel):
username: constr(min_length=3, max_length=50, regex='^[a-zA-Z0-9]+$')
6. Complex Types:
List[X]: List of items of type X.
from typing import List
from pydantic import BaseModel
class Items(BaseModel):
names: List[str]
Tuple[X, Y]: Tuple where the first element is of type X and the second element is of type Y.
from typing import Tuple
from pydantic import BaseModel
class Point(BaseModel):
coordinates: Tuple[float, float]
Dict[K, V]: Dictionary with keys of type K and values of type V.
from typing import Dict
from pydantic import BaseModel
class Scores(BaseModel):
results: Dict[str, int]
Set[X]: Set of items of type X.
from typing import Set
from pydantic import BaseModel
class Tags(BaseModel):
keywords: Set[str]
7. Date and Time:
date: Date (without time)
from datetime import date
from pydantic import BaseModel
class Event(BaseModel):
event_date: date
datetime: Date and time
from datetime import datetime
from pydantic import BaseModel
class Appointment(BaseModel):
timestamp: datetime
time: Time (without date)
from datetime import time
from pydantic import BaseModel
class Reminder(BaseModel):
alarm_time: time
8. Special Types:
Any: Any data type
Byte: Byte string
from pydantic import BaseModel
class File(BaseModel):
content: bytes
Custom Validators:
You can use the @validator(field_validator) and @root_validator(model_validator) decorators to create custom validators.
These types allow you to define and validate a wide range of data structures, making Pydantic a powerful tool for ensuring data integrity in your applications.
Posted on July 22, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024