BudiBadu Logo
Samplebadu

FastAPI by Example: Pydantic Field Types

FastAPI 0.100+

Pydantic offers a rich set of specialized field types beyond standard Python types. This sample code shows how to use types like `EmailStr`, `HttpUrl`, and `UUID` for robust data validation.

Code

from fastapi import FastAPI
from pydantic import BaseModel, EmailStr, HttpUrl, Field
from uuid import UUID, uuid4
from datetime import datetime

app = FastAPI()

class UserProfile(BaseModel):
    user_id: UUID = Field(default_factory=uuid4)
    email: EmailStr
    website: HttpUrl
    joined_at: datetime = Field(default_factory=datetime.now)
    age: int = Field(gt=0, lt=120, description="User age in years")

@app.post("/users/")
async def create_user(user: UserProfile):
    return {
        "user_id": user.user_id,
        "email": user.email,
        "website": user.website,
        "is_adult": user.age >= 18
    }

Explanation

Pydantic provides specialized types that go far beyond standard integers and strings. Types like EmailStr and HttpUrl automatically validate that the input string conforms to the expected format, such as a valid email address or a properly formed URL. This validation adheres to standard RFCs and saves developers from writing complex and error-prone regular expression validators manually.

The Field function allows for extensive customization of individual model fields. Developers can set default values using factory functions, such as uuid4 for generating unique identifiers, ensuring that every new record has a distinct ID without manual intervention. Additionally, numeric constraints like gt (greater than) or lt (less than) can be applied directly within the Field definition, enforcing business logic at the data entry point.

Using these specific types ensures data integrity at the boundary of the application. If a client sends an invalid email or a malformed URL, the request is rejected immediately with a clear 422 error message. This prevents bad data from ever polluting the database or internal logic, and provides immediate, actionable feedback to the API consumer.

Code Breakdown

10
EmailStr requires the email-validator library. It ensures the string looks like a valid email address.
9
default_factory=uuid4 calls the uuid4 function to generate a new UUID every time a model is instantiated.
12
default_factory=datetime.now sets the default value to the current timestamp when the object is created.
13
Field(gt=0, lt=120) enforces that the age must be greater than 0 and less than 120.