Table of Contents
Building a Python Flask API with Database Integration for Front-End Frameworks
In this tutorial, we’ll enhance our Python Flask API to interact with a database, providing a more realistic scenario for full-stack development. We’ll use MySQL as our database for this example, but the principles can be applied to other databases like Oracle or PostgreSQL.
Part 1: Setting Up the Flask Backend with MySQL
Prerequisites
- Python installed on your computer.
- MySQL Server installed and running.
- Basic knowledge of SQL for setting up a database.
Step 1: Creating a New Python Environment
Create and activate a virtual environment for your project:
python -m venv my-flask-api
# Activate the virtual environment
Code language: PHP (php)
Step 2: Installing Flask and MySQL Connector
Install Flask and a MySQL connector (like mysql-connector-python
):
pip install Flask mysql-connector-python
File Structure Overview
Your project directory will now look like this:
my-flask-api/
|-- venv/ # Virtual environment files
|-- app.py # Main application file
|-- requirements.txt # Project dependencies
|-- .env # Environment variables (optional)
Code language: PHP (php)
Step 3: Setting Up MySQL Database
MySQL is an open-source relational database management system (RDBMS) that uses Structured Query Language (SQL) for database management. It is known for its high performance, reliability, and ease of use. MySQL is widely used in web applications and is a key component of the LAMP (Linux, Apache, MySQL, PHP/Python/Perl) software stack. It offers cross-platform support and features robust data security, making it suitable for both small and large-scale applications. MySQL’s scalability and compatibility with various programming languages make it a popular choice for developers and businesses.
- Create a Database: Use MySQL Workbench or command-line tools to create a new database.
- Create a Table: Create a table named
users
with fields likeid
,username
, andpassword
.
Step 4: Creating the Flask Application
Create a file app.py
and set up Flask to connect to your MySQL database.
app.py:
from flask import Flask, jsonify, request
import mysql.connector
from mysql.connector import Error
app = Flask(__name__)
def create_connection():
connection = None
try:
connection = mysql.connector.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database'
)
except Error as e:
print(f"The error '{e}' occurred")
return connection
@app.route('/register', methods=['POST'])
def register():
conn = create_connection()
cursor = conn.cursor()
data = request.json
query = "INSERT INTO users (username, password) VALUES (%s, %s)"
cursor.execute(query, (data['username'], data['password']))
conn.commit()
cursor.close()
conn.close()
return jsonify({'message': 'User registered successfully'}), 201
if __name__ == '__main__':
app.run(debug=True)
Code language: JavaScript (javascript)
Explanation
- Database Connection:
create_connection
function to connect to your MySQL database. - Register Endpoint: Inserts user data into the
users
table.
Step 5: Running the Flask Application
Execute app.py
to start your Flask API:
python app.py
Code language: CSS (css)
Your API will be available at http://localhost:5000
.
Part 2: Integrating Flask Backend with Front-End Frameworks
To connect your Flask API with a front-end framework (Angular, React, or Vue), update the front-end application to send HTTP requests to your Flask backend.
Front-End Changes
- Axios or HttpClientModule: Use Axios (for React/Vue) or Angular’s
HttpClientModule
to make HTTP requests. - Update Components: Modify components to send HTTP POST requests to
http://localhost:5000/register
with user data. - Handling CORS: If you encounter CORS issues, install Flask-CORS in your Flask application and configure it as shown earlier.
Conclusion
You’ve successfully integrated a Python Flask API with a MySQL database, a crucial step in full-stack development. This guide covered setting up a basic Flask application, connecting to a MySQL database, and creating an API endpoint for user registration. As you advance, explore deeper aspects of Flask and database management, enhance your API’s capabilities, and experiment with integrating different front-end frameworks, check out the Flask documentation to learn more and when you are ready to start your own website check out this comprehensive guide. Happy coding in your full-stack journey!