Using an ORM with FastAPI

Kasper Junge
2 min readJun 16, 2023

--

In this blog post, we will discuss the steps to setup and work with an ORM in FastAPI, aiming to create more maintainable and efficient code.

No time to waste, let’s get started 🏃‍♂️

What is an ORM?

An Object-Relational Mapping (ORM) is a programming technique used to manipulate your database, like querying, updating, or deleting data, using an object-oriented paradigm. In Python, there are several libraries for ORM, but for this tutorial, we'll use SQLModel, which plays nicely with FastAPI and allows you to work with SQLAlchemy and Pydantic simultaneously.

Step 1: Installing SQLModel

Before we start, ensure Python 3.6 or later is installed. Then, install FastAPI and SQLModel using pip:

pip install fastapi[all] sqlmodel

Step2: Setting up the Database Model

Let's start by defining a simple model. Models are python classes that define the structure of your database tables and their relationships:

from sqlmodel import SQLModel, Field

class Book(SQLModel, table=True):
id: int = Field(default=None, primary_key=True)
title: str
author: str
year: int

In this Book model, id, title, author, and year represent the columns of our database table.

Step 3: Creating the Database

Here, we will create a SQLite database for our example:

from sqlmodel import Session, SQLModel, create_engine

sqlite_url = "sqlite:///books.db"
engine = create_engine(sqlite_url)

def create_db_and_tables():
SQLModel.metadata.create_all(engine)

Running create_db_and_tables() will create a new SQLite database with a books table.

Step 4: Interacting with the Database

Now that our database is set up, we can start interacting with it. For instance, to insert data into our database, we can create a new Book instance and add it to our session:

def create_book(book: Book):
with Session(engine) as session:
session.add(book)
session.commit()

Here's how you'd use this function:

new_book = Book(title="1984", author="George Orwell", year=1949)
create_book(new_book)

Fetching data from the database is straightforward as well:

def get_books():
with Session(engine) as session:
books = session.exec(Book.select()).all()
return books

This function retrieves all the books in the database.

Step 5: Integrating with FastAPI

FastAPI integrates well with SQLModel. Let's define some routes for creating and retrieving books:

from fastapi import FastAPI
app = FastAPI()

@app.post("/books/")
async def create_book_endpoint(book: Book):
create_book(book)
return {"message": "Book created"}

@app.get("/books/")
async def get_books_endpoint():
books = get_books()
return {"books": books}

And that's it! We have a simple FastAPI application that uses SQLModel as an ORM.

Thank you for taking the time to read this! I sincerely hope that your time was well-spent.

https://chat.openai.com/share/69589825-a589-488a-98c0-a462fe797c36

--

--

Kasper Junge

Machine Learning Engineer 👨‍💻 AI, LLMs, Deep Learning, Python 🔥