DEV Community

Sivak Ihor
Sivak Ihor

Posted on

Validation in FastApi

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
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

float: Floating-point number

from pydantic import BaseModel

class Product(BaseModel):
    price: float
Enter fullscreen mode Exit fullscreen mode

str: String

from pydantic import BaseModel

class User(BaseModel):
    username: str

Enter fullscreen mode Exit fullscreen mode

bool: Boolean value (True or False)

from pydantic import BaseModel

class Settings(BaseModel):
    is_active: bool

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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]+$')
Enter fullscreen mode Exit fullscreen mode

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]

Enter fullscreen mode Exit fullscreen mode

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]

Enter fullscreen mode Exit fullscreen mode

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]

Enter fullscreen mode Exit fullscreen mode

Set[X]: Set of items of type X.

from typing import Set
from pydantic import BaseModel

class Tags(BaseModel):
    keywords: Set[str]

Enter fullscreen mode Exit fullscreen mode

7. Date and Time:
date: Date (without time)

from datetime import date
from pydantic import BaseModel

class Event(BaseModel):
    event_date: date

Enter fullscreen mode Exit fullscreen mode

datetime: Date and time

from datetime import datetime
from pydantic import BaseModel

class Appointment(BaseModel):
    timestamp: datetime

Enter fullscreen mode Exit fullscreen mode

time: Time (without date)

from datetime import time
from pydantic import BaseModel

class Reminder(BaseModel):
    alarm_time: time

Enter fullscreen mode Exit fullscreen mode

8. Special Types:

Any: Any data type
Byte: Byte string

from pydantic import BaseModel

class File(BaseModel):
    content: bytes
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)