This guide uses SQLModel, which is built on top of SQLAlchemy and designed specifically for FastAPI. You can also use SQLAlchemy directly if needed.
Install Dependencies
First, install SQLModel which includes SQLAlchemy:Database Setup
1
Create the Database Engine
Set up the database connection and engine. For this example, we’ll use SQLite:
The
check_same_thread: False argument is needed only for SQLite. It allows multiple threads to access the same connection.2
Define Your Models
Create SQLModel classes that represent your database tables:Setting
table=True tells SQLModel this is a database table model, not just a Pydantic model.3
Create Database Tables
Use a startup event to create all tables:
Session Dependency Injection
The key to working with databases in FastAPI is using dependency injection for database sessions.Create a Session Dependency
- Creates a new session for each request
- Automatically closes the session when the request completes
- Handles cleanup even if an exception occurs
Use Annotated for Cleaner Code
SessionDep instead of Session = Depends(get_session) in every endpoint.
CRUD Operations
Create - Add New Records
session.add()- Adds the object to the sessionsession.commit()- Commits the transaction to the databasesession.refresh()- Refreshes the object to get auto-generated values (like ID)
Read - Query Records
session.get() is a convenient method to fetch by primary key. Use select() for more complex queries.Update - Modify Records
exclude_unset=Trueonly includes fields that were actually providedsqlmodel_update()updates the model with the new data
Delete - Remove Records
Multiple Models for Input/Output
For better security and API design, create separate models:response_model to control what gets returned:
Complete Example
Database URLs
For different databases, use the appropriate connection string:Next Steps
- Learn about async SQL databases for better performance
- Explore advanced SQLModel features like relationships and joins
- Implement connection pooling for production deployments