FastAPI - Beginner to Pro / Large Production Database Setup

Connect FastAPI to MySQL

πŸ”Œ Connecting FastAPI to MySQL

Now that our database is fully set up, it’s time to connect our FastAPI backend to MySQL.

This is a major backend milestone β€” we’re officially moving from SQLite (development) to a production-style MySQL database.


πŸ“¦ Step 1: Install the Required Dependency

<aside> πŸ’‘

Make sure Virtual Environment is active and You are in TodoApp

</aside>

To connect FastAPI (via SQLAlchemy) to MySQL, we need a driver.

Run:

pip install pymysql

We are installing PyMySQL, which allows Python to communicate with MySQL.

Once installed, you're ready to update your configuration.


πŸ—‚οΈ Step 2: Update database.py

Open your database.py file.

We are replacing SQLite with MySQL.

πŸ”„ Change the Database URL

From (SQLite):

SQLALCHEMY_DATABASE_URL = 'sqlite:///./todosapp.db'

To (MySQL):

SQLALCHEMY_DATABASE_URL = 'mysql+pymysql://root:test1234!@127.0.0.1:3306/TodoApplicationDatabase'

Let’s break this down:

  • mysql+pymysql β†’ Database type + driver

  • root β†’ Username

  • test1234! β†’ Password (your passoword)

  • 127.0.0.1:3306 β†’ Local machine + default MySQL port

  • TodoApplicationDatabase β†’ Our schema name

This tells SQLAlchemy to connect to our MySQL database instead of SQLite.


βš™οΈ Step 3: Update create_engine

Previously (for SQLite), we had:

engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={'check_same_thread': False})

The check_same_thread argument is required only for SQLite.

Since we are now using MySQL, remove it:

engine = create_engine(SQLALCHEMY_DATABASE_URL)

Much cleaner. βœ…


πŸš€ Step 4: Start the Application

Open your terminal and run:

uvicorn main:app --reload

Now your FastAPI backend is connected to MySQL.


πŸ§ͺ Step 5: Test the Connection

πŸ‘€ Create two User

Go to your browser β†’ Swagger UI β†’ Create a user.

Click Execute.

You should see:

  • Status Code β†’ 201

  • Response Body β†’ null

This means the request succeeded.

{
	"username": "codeveda",
	"email": "codeveda@gmail.com",
	"first_name": "code",
	"last_name": "veda",
	"password": "test123",
	"role": ""
}
{
	"username": "testuser",
	"email": "test@gmail.com",
	"first_name": "test",
	"last_name": "user",
	"password": "test123",
	"role": ""
}

πŸ”Ž Verify Users

Open MySQL Workbench and run:

SELECT * FROM users;

You should now see two records inside your MySQL database.

πŸŽ‰ That confirms FastAPI is writing directly to MySQL.


πŸ“ Verify Todos

Now check todos:

SELECT * FROM todos;

You’ll see:

No records yet.

Perfect.


βœ… Create a Todo

Go back to your browser and create a todo.

Click Execute β†’ You’ll get:

  • Status Code β†’ 201

  • Response Body β†’ null

Now return to MySQL and run:

SELECT * FROM todos;

You should now see your new todo record.