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
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:
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
Explanation:
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.
Comments
Post a Comment