Building a Robust FastAPI CRUD Application with SQLAlchemy, Pydantic, and Uvicorn: A Step-by-Step Guide

Introduction

In this tutorial, we'll walk through creating a basic CRUD (Create, Read, Update, Delete) application using FastAPI, SQLAlchemy, Pydantic and Uvicorn. We'll build a simple project named `dog_fastapi_crud` that manages dog data.


Prerequisites

Before starting, ensure you have Python installed. You can download the latest version from the official Python website(https://www.python.org/).


Step 1: Setting Up the Environment

First, install the latest version of Python. 

python --version

Once installed, download `get-pip.py` file to install pip and upgrade it to the latest version.

python -m pip install --upgrade pip

Next, create a virtual environment for your project and activate it. This helps manage dependencies and keep your project isolated from other Python projects on your machine.

python -m venv venv

venv\Scripts\activate

Step 2: Installing Required Packages

Install the required packages: FastAPI, SQLAlchemy, Pydantic and Uvicorn.

pip install fastapi sqlalchemy pydantic uvicorn


Step 3: Setting Up Project Structure

Set up your project directory structure as shown below:

dog_fastapi_crud/
├── dog_app/
│   ├── __init__.py
│   ├── main.py
│   ├── models.py
│   ├── schemas.py
│   ├── crud.py
│   └── database.py
└── venv/

Step 4: Creating Models with SQLAlchemy

In the `models.py` file, define our database models. Here, we create a `Dog` model representing our table in the database.

# dog_app/models.py

from sqlalchemy import create_engine, Column, Integer, String

from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy.orm import sessionmaker


DATABASE_URL = "sqlite:///./test.db"


engine = create_engine(DATABASE_URL)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()


class Dog(Base):

    __tablename__ = "dogs"

    id = Column(Integer, primary_key=True, index=True)

    name = Column(String, index=True)

    age = Column(Integer)

Explanation:

=> `DATABASE_URL` specifies the SQLite database file.

=> `engine` connects to the database.

=> `SessionLocal` creates database sessions.

=> `Base` is the base class for our ORM models.

=> `Dog` is our model class representing the `dogs` table with columns: `id`, `name`, and `age`.


Step 5: Creating Pydantic Schemas

In the `schemas.py` file, define Pydantic models. These models help validate and serialize our data.

# dog_app/schemas.py

from pydantic import BaseModel


class DogBase(BaseModel):

    name: str

    age: int


class DogCreate(DogBase):

    pass


class DogRead(DogBase):

    id: int


    class Config:

        orm_mode = True


class DogResponse(BaseModel):

    id: int

    name: str

    age: int

Explanation:

=> `DogBase` is the base schema with common fields.

=> `DogCreate` inherits from `DogBase` and is used for input validation when creating a new dog.

=> `DogRead` is used for reading dog data and includes the `id` field. The `Config` class with `orm_mode = True` tells Pydantic to read data as ORM objects.

=> `DogResponse` is used for responses, including all fields of the `Dog` model.


Step 6: Creating CRUD Operations

In the `crud.py` file, define functions to handle CRUD operations.

# dog_app/crud.py

from sqlalchemy.orm import Session

from . import models, schemas


def get_dog(db: Session, dog_id: int):

    return db.query(models.Dog).filter(models.Dog.id == dog_id).first()


def get_dogs(db: Session, skip: int = 0, limit: int = 10):

    return db.query(models.Dog).offset(skip).limit(limit).all()


def create_dog(db: Session, dog: schemas.DogCreate):

    db_dog = models.Dog(name=dog.name, age=dog.age)

    db.add(db_dog)

    db.commit()

    db.refresh(db_dog)

    return db_dog


def update_dog(db: Session, dog_id: int, dog: schemas.DogCreate):

    db_dog = db.query(models.Dog).filter(models.Dog.id == dog_id).first()

    if db_dog is None:

        return None

    db_dog.name = dog.name

    db_dog.age = dog.age

    db.commit()

    db.refresh(db_dog)

    return db_dog


def delete_dog(db: Session, dog_id: int):

    db_dog = db.query(models.Dog).filter(models.Dog.id == dog_id).first()

    if db_dog is None:

        return None

    db.delete(db_dog)

    db.commit()

    return db_dog

Explanation:

=> `get_dog` retrieves a dog by its ID.

=> `get_dogs` retrieves a list of dogs with optional pagination.

=> `create_dog` creates a new dog in the database.

=> `update_dog` updates an existing dog in the database.

=> `delete_dog` deletes a dog from the database.


Step 7: Setting Up the Database

In the `database.py` file, set up our database initialization and session management.

# dog_app/database.py

from .models import Base, engine, SessionLocal


def init_db():

    Base.metadata.create_all(bind=engine)


def get_db():

    db = SessionLocal()

    try:

        yield db

    finally:

        db.close()

Explanation:

- `init_db` initializes the database by creating tables based on our models.

- `get_db` provides a session generator that will be used in our FastAPI endpoints.


Step 8: Creating FastAPI Endpoints

In the `main.py` file, set up our FastAPI application and define the endpoints for CRUD operations.

# dog_app/main.py
from fastapi import FastAPI, HTTPException, Depends
from sqlalchemy.orm import Session
from dog_app import models, schemas, crud, database

# Initialize the database
database.init_db()

app = FastAPI()

@app.post("/dog/add", response_model=schemas.DogResponse)
def create_dog(dog: schemas.DogCreate, db: Session = Depends(database.get_db)):
    return crud.create_dog(db=db, dog=dog)

@app.get("/dog/all", response_model=list[schemas.DogResponse])
def read_dogs(skip: int = 0, limit: int = 10, db: Session = Depends(database.get_db)):
    dogs = crud.get_dogs(db=db, skip=skip, limit=limit)
    return dogs

@app.get("/dog/fetch/{dog_id}", response_model=schemas.DogResponse)
def read_dog(dog_id: int, db: Session = Depends(database.get_db)):
    dog = crud.get_dog(db=db, dog_id=dog_id)
    if dog is None:
        raise HTTPException(status_code=404, detail="Dog not found")
    return dog

@app.put("/dog/update/{dog_id}", response_model=schemas.DogResponse)
def update_dog(dog_id: int, dog: schemas.DogCreate, db: Session = Depends(database.get_db)):
    db_dog = crud.update_dog(db=db, dog_id=dog_id, dog=dog)
    if db_dog is None:
        raise HTTPException(status_code=404, detail="Dog not found")
    return db_dog

@app.delete("/dog/remove/{dog_id}", response_model=schemas.DogResponse)
def delete_dog(dog_id: int, db: Session = Depends(database.get_db)):
    db_dog = crud.delete_dog(db=db, dog_id=dog_id)
    if db_dog is None:
        raise HTTPException(status_code=404, detail="Dog not found")
    return db_dog

Explanation:

- `create_dog` endpoint creates a new dog.
- `read_dogs` endpoint retrieves a list of dogs with pagination.
- `read_dog` endpoint retrieves a single dog by ID.
- `update_dog` endpoint updates a dog by ID.
- `delete_dog` endpoint deletes a dog by ID.

Step 9: Running the Application

After creating and finishing all the files, run the application using the Uvicorn server with the following command:

uvicorn dog_app.main:app --reload


Step 10: Testing the API

To test our API, navigate to `http://127.0.0.1:8000/docs` to access the Swagger UI and perform CRUD operations successfully.

Below are the endpoints that we have created and you can see that in Swagger UI doc,


POST /dog/add - Create a new dog

GET /dog/all - Get all dogs

GET /dog/fetch/{dog_id} - Get dog by ID

PUT /dog/update/{dog_id} - Update an existing dog

DELETE /dog/remove/{dog_id} - Delete a dog


Conclusion

In this tutorial, we've built a simple FastAPI application to manage dog data using SQLAlchemy for ORM, Pydantic for data validation, and Uvicorn as the ASGI server. This example can serve as a foundation for more complex applications, demonstrating the power and simplicity of FastAPI.

If you have any questions or need further clarification, feel free to leave a comment below. Happy coding!

Comments