Skip to main content
FastAPI works seamlessly with SQL databases through SQLModel, a library that combines SQLAlchemy and Pydantic for a powerful database integration.
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

This 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

Now you can use SessionDep instead of Session = Depends(get_session) in every endpoint.
Never create a global session. Always use dependency injection to ensure each request gets its own session.

CRUD Operations

Create - Add New Records

The process:
  1. session.add() - Adds the object to the session
  2. session.commit() - Commits the transaction to the database
  3. session.refresh() - Refreshes the object to get auto-generated values (like ID)

Read - Query Records

Query a single record:
session.get() is a convenient method to fetch by primary key. Use select() for more complex queries.

Update - Modify Records

Key points:
  • exclude_unset=True only includes fields that were actually provided
  • sqlmodel_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:
Then use response_model to control what gets returned:

Complete Example

Database URLs

For different databases, use the appropriate connection string:
Never hardcode credentials in your code. Use environment variables:

Next Steps

  • Learn about async SQL databases for better performance
  • Explore advanced SQLModel features like relationships and joins
  • Implement connection pooling for production deployments