π 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 + driverrootβ Usernametest1234!β Password (your passoword)127.0.0.1:3306β Local machine + default MySQL portTodoApplicationDatabaseβ 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.
