Skip to main content

Show usage of Python Pydantic class with FastAPI

Using Pydantic with FastAPI for Data Validation 

FastAPI is a modern Python framework that makes building APIs fast and easy. It integrates with Pydantic to provide automatic data validation and serialization. In this post, we'll explore how to use Pydantic models inside a FastAPI app.


1️⃣ Install FastAPI & Uvicorn

Before we start, install FastAPI and Uvicorn using pip:

pip install fastapi uvicorn pydantic
  • FastAPI: The API framework.
  • Uvicorn: ASGI server to run the FastAPI app.

2️⃣ Creating a Simple FastAPI App

Let's create a basic FastAPI app that accepts user data, validates it, and returns a response.

📌 Code: FastAPI with Pydantic

from fastapi import FastAPI
from pydantic import BaseModel, EmailStr

app = FastAPI()

# Define a Pydantic model
class User(BaseModel):
    id: int
    name: str
    age: int
    email: EmailStr  # Validates email format

# Endpoint to create a user
@app.post("/users/")
async def create_user(user: User):
    return {"message": "User created successfully", "user": user}

# Run using: uvicorn filename:app --reload

3️⃣ Running the FastAPI App

Save the file as main.py and run:

uvicorn main:app --reload

Now, open your browser and visit:


4️⃣ Testing API with JSON Data

Use Swagger UI or Postman to send a POST request to /users/ with JSON:

{
  "id": 1,
  "name": "Alice",
  "age": 25,
  "email": "alice@example.com"
}

Success Response:

{
  "message": "User created successfully",
  "user": {
    "id": 1,
    "name": "Alice",
    "age": 25,
    "email": "alice@example.com"
  }
}

🚫 Validation Error (Invalid Email):

{
  "detail": [
    {
      "loc": ["body", "email"],
      "msg": "value is not a valid email address",
      "type": "value_error.email"
    }
  ]
}

5️⃣ Adding Custom Validation in Pydantic

We can enforce custom rules using @validator.

📌 Example: Restrict Age to 18+

from pydantic import validator

class User(BaseModel):
    id: int
    name: str
    age: int
    email: EmailStr

    @validator("age")
    def validate_age(cls, value):
        if value < 18:
            raise ValueError("Age must be 18 or older")
        return value

Now, if a user under 18 tries to register, they’ll get a validation error.


6️⃣ Using Nested Pydantic Models

For complex objects, we can nest Pydantic models.

📌 Example: User with Address

from typing import List

class Address(BaseModel):
    street: str
    city: str
    zip_code: str

class User(BaseModel):
    id: int
    name: str
    age: int
    email: EmailStr
    address: Address  # Nested Pydantic Model

@app.post("/users/")
async def create_user(user: User):
    return {"message": "User created", "user": user}

Now, JSON requests must include an address:

{
  "id": 2,
  "name": "Bob",
  "age": 30,
  "email": "bob@example.com",
  "address": {
    "street": "456 Elm St",
    "city": "Los Angeles",
    "zip_code": "90001"
  }
}

7️⃣ Returning Pydantic Models as API Responses

You can enforce structured responses with response_model.

📌 Example:

@app.post("/users/", response_model=User)
async def create_user(user: User):
    return user

Now, FastAPI ensures that responses match the User model.


🎯 Conclusion

FastAPI + Pydantic provides: ✅ Automatic data validation
Easy JSON serialization
Swagger UI for testing
Custom validators for business rules


Comments

Popular posts from this blog

Simple Linear Regression - and Related Regression Loss Functions

Today's Topics: a. Regression Algorithms  b. Outliers - Explained in Simple Terms c. Common Regression Metrics Explained d. Overfitting and Underfitting e. How are Linear and Non Linear Regression Algorithms used in Neural Networks [Future study topics] Regression Algorithms Regression algorithms are a category of machine learning methods used to predict a continuous numerical value. Linear regression is a simple, powerful, and interpretable algorithm for this type of problem. Quick Example: These are the scores of students vs. the hours they spent studying. Looking at this dataset of student scores and their corresponding study hours, can we determine what score someone might achieve after studying for a random number of hours? Example: From the graph, we can estimate that 4 hours of daily study would result in a score near 80. It is a simple example, but for more complex tasks the underlying concept will be similar. If you understand this graph, you will understand this blog. Sim...

What problems can AI Neural Networks solve

How does AI Neural Networks solve Problems? What problems can AI Neural Networks solve? Based on effectiveness and common usage, here's the ranking from best to least suitable for neural networks (Classification Problems, Regression Problems and Optimization Problems.) But first some Math, background and related topics as how the Neural Network Learn by training (Supervised Learning and Unsupervised Learning.)  Background Note - Mathematical Precision vs. Practical AI Solutions. Math can solve all these problems with very accurate results. While Math can theoretically solve classification, regression, and optimization problems with perfect accuracy, such calculations often require impractical amounts of time—hours, days, or even years for complex real-world scenarios. In practice, we rarely need absolute precision; instead, we need actionable results quickly enough to make timely decisions. Neural networks excel at this trade-off, providing "good enough" solutions in seco...

Activation Functions in Neural Networks

  A Guide to Activation Functions in Neural Networks 🧠 Question: Without activation function can a neural network with many layers be non-linear? Answer: Provided at the end of this document. Activation functions are a crucial component of neural networks. Their primary purpose is to introduce non-linearity , which allows the network to learn the complex, winding patterns found in real-world data. Without them, a neural network, no matter how deep, would just be a simple linear model. In the diagram below the f is the activation function that receives input and send output to next layers. Commonly used activation functions. 1. Sigmoid Function 2. Tanh (Hyperbolic Tangent) 3. ReLU (Rectified Linear Unit - Like an Electronic Diode) 4. Leaky ReLU & PReLU 5. ELU (Exponential Linear Unit) 6. Softmax 7. GELU, Swish, and SiLU 1. Sigmoid Function                       The classic "S-curve," Sigmoid squashes any input value t...