Back to Blog

Build REST APIs with Pydantic Validation - Python FastAPI Tutorial -#38

Sandy LaneSandy Lane

Video: Build REST APIs with Pydantic Validation - Python FastAPI Tutorial -#38 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Build REST APIs with Pydantic Validation - Python FastAPI Tutorial

FastAPI is a modern, fast Python web framework that simplifies building REST APIs with automatic data validation using Pydantic models. In this tutorial, you'll learn how to create endpoints that handle GET and POST requests, validate request data, and implement full CRUD operations with async support.

Code

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional
from fastapi.testclient import TestClient

app = FastAPI()

# Pydantic model for employee data validation
class Employee(BaseModel):
  id: int
  name: str
  age: Optional[int] = None
  department: Optional[str] = None

# In-memory "database"
employees = {}

# Create employee (POST)
@app.post("/employees/")
async def create_employee(emp: Employee):
  if emp.id in employees:
    raise HTTPException(status_code=400, detail="Employee already exists")
  employees[emp.id] = emp
  return emp

# Read employee (GET)
@app.get("/employees/{emp_id}")
async def read_employee(emp_id: int):
  if emp_id not in employees:
    raise HTTPException(status_code=404, detail="Employee not found")
  return employees[emp_id]

# Update employee (PUT)
@app.put("/employees/{emp_id}")
async def update_employee(emp_id: int, emp: Employee):
  if emp_id != emp.id:
    raise HTTPException(status_code=400, detail="ID mismatch")
  if emp_id not in employees:
    raise HTTPException(status_code=404, detail="Employee not found")
  employees[emp_id] = emp
  return emp

# Delete employee (DELETE)
@app.delete("/employees/{emp_id}")
async def delete_employee(emp_id: int):
  if emp_id not in employees:
    raise HTTPException(status_code=404, detail="Employee not found")
  del employees[emp_id]
  return {"detail": "Employee deleted"}

# Example test with TestClient (no server needed)
client = TestClient(app)
def test_create_and_get_employee():
  response = client.post("/employees/", json={"id":1, "name":"Alice"})
  assert response.status_code == 200
  response = client.get("/employees/1")
  assert response.json()["name"] == "Alice"

Key Points

  • FastAPI uses Pydantic models to automatically validate and parse incoming JSON request bodies.
  • CRUD endpoints can be defined with async functions and HTTP method decorators like @app.post and @app.get.
  • HTTPException allows returning proper HTTP error codes and messages when validation or logic fails.
  • TestClient enables testing FastAPI routes without running a server, facilitating quick API tests.
  • Pydantic v2 introduces model_dump() for easy serialization of model instances to dictionaries.