First, create a new directory for your project and navigate into it:
mkdir fastapi_sqlalchemy_project
cd fastapi_sqlalchemy_project
Create a virtual environment and activate it:
python -m venv venv
source venv/bin/activate # For Linux/Mac
.\venv\Scripts\activate # For Windows
Install the required packages:
pip install fastapi sqlalchemy uvicorn
Let’s create a simple model for a User
table. Create a file named models.py
:
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
name = Column(String)
email = Column(String, unique=True, index=True)
Create a file named database.py
to configure the database connection. Here, we’ll use SQLite for simplicity:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
In the database.py
file, we’ve already created a session factory SessionLocal
. To use it in our API endpoints, we can create a dependency function:
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
Create a file named main.py
to define our API endpoints:
from fastapi import Depends, FastAPI
from sqlalchemy.orm import Session
from .models import User
from .database import get_db
app = FastAPI()
@app.post("/users/")
def create_user(user: User, db: Session = Depends(get_db)):
db_user = User(name=user.name, email=user.email)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
@app.get("/users/{user_id}")
def read_user(user_id: int, db: Session = Depends(get_db)):
user = db.query(User).filter(User.id == user_id).first()
return user
When working with database operations, it’s important to handle errors and manage transactions properly. In the create_user
endpoint above, if an error occurs during the db.commit()
operation, SQLAlchemy will roll back the transaction automatically because we set autocommit=False
in the session factory.
get_db
function, using dependency injection makes it easier to manage database sessions and test your code.Integrating FastAPI with SQLAlchemy provides a powerful combination for building high - performance web APIs with a reliable database backend. By following the steps outlined in this blog, you can set up a basic project, define database models, configure the database connection, create database sessions, and build API endpoints. Additionally, adhering to best practices will help you write clean, maintainable, and robust code.