FastAPI SQLAlchemy ORM
What is SQLAlchemy ORM?
SQLAlchemy ORM (Object-Relational Mapping) is a library that provides a way to interact with relational databases using Python objects. Instead of writing raw SQL queries, you define models in Python that represent tables in a database. SQLAlchemy translates these Python objects into SQL queries and executes them against the database, allowing you to interact with the database using Python code.
How do you set up SQLAlchemy ORM with FastAPI?
To set up SQLAlchemy with FastAPI, you need to install the necessary dependencies and configure a database connection. You can then define models, create database sessions, and use these sessions in your FastAPI routes to interact with the database.
Example of setting up SQLAlchemy with FastAPI:
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
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)
Base = declarative_base()
In this example, an SQLite database connection is configured using SQLAlchemy. The engine is used to connect to the database, and the SessionLocal class creates database sessions. The Base class is used to define models.
How do you define SQLAlchemy models in FastAPI?
SQLAlchemy models are Python classes that represent tables in a relational database. Each model class defines attributes that map to columns in the table, and these attributes are defined using SQLAlchemy column types.
Example of defining a SQLAlchemy model:
from sqlalchemy import Column, Integer, String
from .database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
email = Column(String, unique=True, index=True)
In this example, the User model represents the users table in the database. The table has three columns: id (primary key), name (indexed), and email (unique and indexed).
How do you create the database tables with SQLAlchemy in FastAPI?
Once the models are defined, you can create the corresponding tables in the database by calling Base.metadata.create_all(), which generates the SQL statements needed to create the tables.
Example of creating tables:
from .database import engine
from .models import Base
Base.metadata.create_all(bind=engine)
In this example, the create_all() method creates the tables in the database based on the models defined in your application.
How do you manage database sessions in FastAPI?
In FastAPI, database sessions are managed by creating session instances using the SessionLocal class. These sessions are used to interact with the database in route handlers. It is important to ensure that the session is properly closed after each request to avoid database connection leaks.
Example of managing database sessions:
from fastapi import Depends
from sqlalchemy.orm import Session
from .database import SessionLocal
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
In this example, the get_db() function creates a new session for each request. The session is automatically closed after the request is processed.
How do you use SQLAlchemy sessions in FastAPI routes?
To use SQLAlchemy sessions in FastAPI routes, you inject the database session into the route function using the Depends function. You can then use the session to perform database operations such as querying or modifying data.
Example of using SQLAlchemy sessions in routes:
from fastapi import Depends, FastAPI
from sqlalchemy.orm import Session
from . import models, schemas, database
app = FastAPI()
@app.get("/users/")
def read_users(db: Session = Depends(database.get_db)):
return db.query(models.User).all()
In this example, the read_users route queries all users from the database using the session. The session is injected into the route via the Depends function and get_db().
How do you add data to the database using SQLAlchemy in FastAPI?
To add data to the database, you create an instance of the model, add it to the session, and commit the session. This inserts the data into the corresponding table in the database.
Example of adding data to the database:
from fastapi import Depends, FastAPI
from sqlalchemy.orm import Session
from . import models, schemas, database
app = FastAPI()
@app.post("/users/")
def create_user(user: schemas.UserCreate, db: Session = Depends(database.get_db)):
db_user = models.User(name=user.name, email=user.email)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
In this example, the create_user route creates a new user by adding the user data to the session and committing the transaction. The db.refresh() method updates the instance with the new ID generated by the database.
How do you query data from the database using SQLAlchemy in FastAPI?
SQLAlchemy allows you to query data using the session's query() method. You can filter, sort, and limit the results using SQLAlchemy's query functions.
Example of querying data from the database:
@app.get("/users/{user_id}")
def read_user(user_id: int, db: Session = Depends(database.get_db)):
return db.query(models.User).filter(models.User.id == user_id).first()
In this example, the read_user route retrieves a user by ID from the database. The filter() method is used to filter the query by the user_id.
How do you update data in the database using SQLAlchemy in FastAPI?
To update data in the database, you query the record you want to update, modify its attributes, and then commit the changes to the session.
Example of updating data:
@app.put("/users/{user_id}")
def update_user(user_id: int, user: schemas.UserUpdate, db: Session = Depends(database.get_db)):
db_user = db.query(models.User).filter(models.User.id == user_id).first()
db_user.name = user.name
db_user.email = user.email
db.commit()
return db_user
In this example, the update_user route updates the user's name and email fields by modifying the existing record and committing the changes.
How do you delete data from the database using SQLAlchemy in FastAPI?
To delete data, you query the record you want to remove, use the delete() method to mark it for deletion, and then commit the session.
Example of deleting data:
@app.delete("/users/{user_id}")
def delete_user(user_id: int, db: Session = Depends(database.get_db)):
db_user = db.query(models.User).filter(models.User.id == user_id).first()
db.delete(db_user)
db.commit()
return {"message": "User deleted"}
In this example, the delete_user route deletes a user from the database by first querying the user by ID, then calling db.delete() and committing the changes.
How do you handle database migrations with SQLAlchemy in FastAPI?
Database migrations help you track and apply schema changes over time. You can use Alembic, a migration tool, alongside SQLAlchemy to handle database migrations in FastAPI. Alembic generates migration scripts based on changes to your models, and you can apply those migrations to your database.
Example of setting up Alembic for migrations:
pip install alembic
alembic init alembic
After setting up Alembic, you can generate and apply migrations as your database schema evolves.