FastAPI is a modern, fast (high-performance), web framework for building APIs with Python. It’s built on standard Python type hints, making it easy to use, while providing a lot of advanced features for developers.
When building a FastAPI application, it’s crucial to separate configuration from the code, especially database connection details, for security and modularity. Using .env files and structured code can make this process more secure and maintainable.
In this article, we will look at integrating FastAPI with MySQL to handle database operations.
Setting up FastAPI with MySQL
1. Setting up the environment:
- Create a new virtual environment:
python3 -m venv env
source env/bin/activate
- Install FastAPI, Uvicorn, and necessary packages:
pip install fastapi uvicorn mysql-connector-python python-dotenv
2. Setting up .env:
Create a `.env` file in your project’s root directory with the following:
3. Connecting to MySQL:
Let’s create a separate `database.py` file to handle all database-related operations:
`database.py`:
Now, in `main.py`, import the connect function:
Creating a Table
Inside `database.py`, create a function to initialize tables:
Invoke this function during the startup of your FastAPI application:
CRUD Operations
Continue to encapsulate database operations within `database.py`. For instance:
Then, in `main.py`, invoke these functions:
Running the Application
Run the FastAPI app using Uvicorn:
uvicorn main:app --reload
This setup ensures a clear separation of concerns, keeps sensitive data out of your main codebase (using .env), and organizes database operations neatly in a separate module. As your application grows, consider adopting more advanced practices like connection pooling, ORM tools, and thorough error handling.
Conclusion
With this, you have a basic FastAPI application integrated with MySQL. Remember to properly manage and close database connections, handle exceptions, and implement other best practices in production environments. This guide is meant to be a starting point, and there’s much more you can do with both FastAPI and MySQL!