Step by Step Guide: Building a FastAPI App with MySQL Database

Posted by


FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. In this tutorial, I will show you how to build a FastAPI app with a MySQL database. We will be using the asyncpg library to interact with the MySQL database asynchronously.

Before we get started, make sure you have Python 3.6 or higher installed on your system. You also need to install FastAPI, uvicorn, and asyncpg. You can install them using pip:

pip install fastapi uvicorn asyncpg

Now, let’s create a new FastAPI app and set up the MySQL database connection.

Step 1: Create a new FastAPI app

Create a new directory for your FastAPI project and change into that directory:

mkdir fastapi_mysql_app
cd fastapi_mysql_app

Create a new Python file called main.py and open it in your favorite code editor:

touch main.py

Step 2: Set up the MySQL database connection

First, import the necessary modules in main.py:

from fastapi import FastAPI, HTTPException
import asyncpg

Next, create a FastAPI app instance:

app = FastAPI()

Now, create a function to connect to the MySQL database:

async def connect_to_db():
    conn = await asyncpg.connect(
        user="your_username",
        password="your_password",
        database="your_database",
        host="your_host",
    )
    return conn

Replace your_username, your_password, your_database, and your_host with your MySQL database credentials.

Step 3: Create API endpoints to interact with the MySQL database

Let’s create a simple API endpoint to fetch all records from a users table in the MySQL database.

@app.get("/users/")
async def get_users():
    conn = await connect_to_db()
    users = await conn.fetch("SELECT * FROM users")
    await conn.close()
    return users

In this endpoint, we create a connection to the MySQL database, fetch all records from the users table, close the connection, and return the results.

Step 4: Run the FastAPI app with uvicorn

To run the FastAPI app, use the following command:

uvicorn main:app --reload

Now, you can access your API at http://localhost:8000/users/ and see the records from the users table.

That’s it! You have successfully built a FastAPI app with a MySQL database. You can now expand your app by adding more API endpoints to perform CRUD operations on the database. Have fun building your FastAPI app!

0 0 votes
Article Rating
33 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@ushared-a-chregion3720
1 month ago

I have one question to it. How can I join tables ?

@ushared-a-chregion3720
1 month ago

really hot stuff Eric, thx for this very good explanation!

@shreyashverma1773
1 month ago

Amazing !!

@nmuyu
1 month ago

this guy is so underrated

@youdontknowme4241
1 month ago

It is showing that could not import module “main”.
I have done everything as per video.
Idk whats wrong?

@bhartendupandya3824
1 month ago

Amazing, loved it! best content.!

@mr_don_key
1 month ago

you didn't make a foreign key in the model 😉 (user_id is just a integer column, instead of a foreign key for id in user table)

@roozensn
1 month ago

Thanks a lot! Very helpful for beginners like me

@azer0013
1 month ago

You did use Sql for chating with the data?

@lapislazuli1949
1 month ago

where is PUT request?

@warisshaikh9474
1 month ago

Super cool and easy steps salut to u sir love from karachi pakistan ❤

@nillsonsilva5896
1 month ago

It works very well, however, how do i do an update for my posts ?

@aestriex
1 month ago

How do we implement HTML/CSS front-end into this application? Also, can a user login/registration system be implemented? (where users can sign up for an account and then make posts, for example)

@dianavaleriaovallevaldes1980
1 month ago

many thankssss!!😿

@abdullahmusheer4238
1 month ago

as a newbie, i have a question, how can i host it so that external users can use it? i know we should secure it (whitelisting ip/tokens etc) but how can i load this python app to the internet for access to external users. thanks

@InspireBeforeExpire-my6fm
1 month ago

working correct

@Kay-ip9fy
1 month ago

Thanks!

@archanan1340
1 month ago

Hii i have one doubt we can connect already existing database and tables also

@witty.coder1
1 month ago

Thats so great sir. I am learning form you

@kal.
1 month ago

where is the video on how to setup the mysql workbench? couldnt find it