Interacting with Databases in FastAPI applications using FastAPI and SQLModel

Posted by


In this tutorial, we will explore how to set up a FastAPI application and interact with a database using SQLModel. FastAPI is a modern, fast (high-performance) web framework for building APIs with Python, and SQLModel is a library that provides a declarative syntax for defining database models in Python.

To get started, let’s first create a new virtual environment and install the necessary packages:

$ python -m venv venv
$ source venv/bin/activate
$ pip install fastapi uvicorn sqlmodel

Next, let’s create a new FastAPI application. Create a new file named main.py and add the following code:

from fastapi import FastAPI
from sqlmodel import Field, Session, SQLModel, create_engine

# Create a new FastAPI app
app = FastAPI()

# Configure the database connection
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"

# Create the database engine
engine = create_engine(SQLALCHEMY_DATABASE_URL)

# Define a model for the database table
class User(SQLModel, table=True):
    id: int = Field(primary_key=True)
    username: str
    email: str

# Create the database table
def create_db_and_tables():
    SQLModel.metadata.create_all(engine)

# Create an endpoint to add a new user to the database
@app.post("/users/")
def create_user(user: User):
    with Session(engine) as session:
        session.add(user)
        session.commit()
        session.refresh(user)
        return user

In this code, we define a User model using SQLModel, which represents a database table with columns for id, username, and email. We also create a create_user endpoint that accepts a User object and adds it to the database.

To create the database table, we call the create_db_and_tables function, which uses the SQLModel.metadata.create_all method to create the table based on our model. We also create a database engine using the create_engine method with the connection URL for an SQLite database.

To run the FastAPI application, use the following command:

$ uvicorn main:app --reload

Now that the application is running, you can test the create_user endpoint using a tool like Postman or cURL. For example, you can send a POST request to http://localhost:8000/users/ with a JSON payload containing the user data:

{
  "username": "johndoe",
  "email": "johndoe@example.com"
}

After sending the request, you should see a response containing the newly created user object with an id assigned by the database.

This is a simple example of how to interact with a database using SQLModel in a FastAPI application. You can extend this by adding more endpoints for CRUD operations, implementing relationships between models, or using different database engines. FastAPI and SQLModel provide a powerful combination for building APIs with Python and interacting with databases in a declarative way.

0 0 votes
Article Rating
20 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@LaichuTV
2 months ago

Bro thank you for creating these videos, deeply respect!

@boholsurf_2749
2 months ago

great video

@fazlehadiazmat7g803
2 months ago

dyed your hair?

@Steve51791
2 months ago

Why should one create subclasses and inherit from a base class? Is there a reason you shouldn't just, for example, put the primary key field in the parent class?

@thierryyolepiot9951
2 months ago

Can you show hoz to set up FastAPI with MySQL and PostGreSQL (especially with the async features)?

@Covalentdesigns
2 months ago

I really like BugBytes content and I found all of the early HTMX content to be very interesting and useful. So I had high hopes for this "full" course, but I am afraid that this course suffers from the same issues that most FastAPI courses on the web do. They don't work with production-ready code and tools. Because production-ready setups are so different due to the tools used, beginners learn the wrong way of coding and setting different parts of FastAPI, and we don't find out until much later. Then we have to relearn how to do everything. I wish people writing tutorials would focus on production because in the end, if you can't deploy it in production, it's useless.

@gerrior
2 months ago

Timestamp: 18:30. Even after adding `None` to the `band_id` at runtime I'm getting "pydantic_core: 1 validation error for AlbumBase" "band_id missing". I am using Progres instead of SQLite.

@djtoon8412
2 months ago

also setting up with postgres docker and traefik .Also an additional content can be sending emails and show how to create email templates

@ayushshende4290
2 months ago

A video on env config and file structure for bigger projects would also be helpful

@tascsolutions6483
2 months ago

Great content! Can you please explain why some tutorials use pydantic models(schemas) AND sql models (models)? I find this confusing and causing issues.

@GregMeece
2 months ago

I couldn't find this in your GitHub repo. Is it published? Thanks for the walkthrough regardless!

@recaseng
2 months ago

Please do more on the crud operations as well as error handlings please

@dixon1e
2 months ago

This is incredibly well produced and deeply informative. Thank you.

@juvewan
2 months ago

Endpoint functions are defined as `async def`, but the db operations inside are all sync, including the get_session depency. This is bad in a real project. async def endpoints are running in an event loop, time cosuming db operations are not awaited, so they will block the event loop.

@opticonor
2 months ago

Lots of value in this video, thanks!!

@catchychazz
2 months ago

Is SQLModel still necessary with SQLAlchemy 2.0?

@djtoon8412
2 months ago

can we also get one for microservices using gRPC

@GerhardGrasberger
2 months ago

Great video! Could you please upload the source code to GitHub?

@beefbox
2 months ago

Hey, do you consider making an unpoly video? I feel like the library is so underrated.

@adhd_arti
2 months ago

Best content!