Skip to content

Databases and ORM

Our post APIs have stored data in a Python list in server memory. Changes remain available while the server runs. But a restart after deployment or a failure resets the list, discarding posts added or edited at runtime.

To retain posts across restarts, store them persistently outside the server's memory. A database stores and manages this data.

Data Flow

The client exchanges requests and responses with the server, which stores and retrieves database data

A server uses a database to handle a request as follows:

  • ① The client sends a request.
  • ② The server asks the database to store or retrieve data.
  • ③ The database returns the result.
  • ④ The server uses that result to respond to the client.

Data stored in the database survives the server stopping, so the server can retrieve it after restarting.

The client request (①) and server response (④) are HTTP messages.

For database operations (②), the server must express what to store or retrieve in a language the database understands. SQL (Structured Query Language) is widely used for these operations. The database executes the SQL and returns results (③), which the server uses in its HTTP response.

HTTP between client and server; SQL and results between server and database

ORM

Developers can write SQL directly in server code. A FastAPI server might keep SQL in Python strings and pass it to the database, then arrange returned rows into Python-friendly lists or dictionaries.

With more relationships, both SQL and result-processing code can become complex. A query joining users, posts, and comments may repeat post information for every comment. The server must group those rows into posts and their comments. ORM (Object-Relational Mapping) helps reduce this conversion work and manage relationships.

An ORM maps relational database tables to classes so you can work with objects. Define the mapping once and reuse it for queries, inserts, and other operations.

The Post class maps to posts, fields map to columns, and an instance maps to one row

An ORM converts query results into Python objects. With the relationship defined, you can access a post's comments through an attribute such as post.comments.

You can retrieve and save data using Python objects without writing SQL yourself. The server still sends SQL to the database: the ORM runs inside the server, generates SQL, and converts results back into objects.

The ORM runs inside the server, sending SQL to the database and receiving results

ORM is not specific to Python. Languages such as Java and C# have ORM tools too.

SQLAlchemy

SQLAlchemy is a widely used Python ORM library. First released in 2006, it has a long development history and a broad collection of tutorials and examples.

The FastAPI documentation teaches database access with SQLModel. Earlier tutorials used SQLAlchemy; they later switched to SQLModel, created by FastAPI's author. SQLModel shares field declarations between database tables and Pydantic models, reducing duplication.

SQLModel itself is built on SQLAlchemy. Understanding the underlying library helps you use SQLModel more deeply. Here we will learn ORM fundamentals with SQLAlchemy and its extensive documentation and examples.

Install SQLAlchemy with your virtual environment active:

$ pip install sqlalchemy

SQLite

SQLAlchemy connects your Python code to a database; it does not replace the database that stores the data. Web services commonly use database servers such as MySQL or PostgreSQL. Our focus is learning ORM usage, so we will use SQLite for its simple setup.

SQLite is a lightweight database often used for local storage in mobile and desktop applications. It keeps tables and data in one file and runs inside the application process. In our service, SQLite executes SQL and reads or writes that file within the FastAPI server.

Python supports SQLite through its standard sqlite3 module, so a typical Python installation needs no separate database installation. We will let the database file be created on the first connection through SQLAlchemy.

Check Your Understanding

Decide whether each statement is true or false.

  1. Data stored only in server memory survives a server process restart.
  2. SQL can instruct a database to store or retrieve data.
  3. An ORM can represent a database row as a Python class instance.
  4. SQLAlchemy removes the need for a database to store data.
  5. SQLite requires a separate database server process.
Answers and Explanations
  1. False — In-memory changes disappear when the process ends.
  2. True — SQL expresses operations such as inserts and queries.
  3. True — An ORM maps tables to classes and rows to objects.
  4. False — SQLAlchemy helps application code use a database; the database stores the data.
  5. False — SQLite runs inside the application and accesses its database file directly.