Activity 49: Python Flask API with SQLALCHEMY integration
Activity 49: Python Flask API with SQLAlchemy Integration
In this activity, we will integrate SQLAlchemy with Flask to create a RESTful API that can interact with a database. SQLAlchemy is an Object Relational Mapper (ORM) for Python that allows us to map database tables to Python classes and perform database operations using Python code.
We will cover the following topics:
Setting up Flask and SQLAlchemy
Creating a Flask API
Creating and Configuring a Database Model
Performing CRUD Operations
Testing the API
1. Setting Up Flask and SQLAlchemy
To begin, we need to install the necessary libraries:
pip install Flask
pip install Flask-SQLAlchemy
Flask: A lightweight web framework for Python.
Flask-SQLAlchemy: An extension for Flask that simplifies working with SQLAlchemy.
2. Creating a Flask API
Start by creating a basic Flask application. In this example, we’ll set up a Flask app and configure it to use SQLAlchemy for database integration.
Basic Setup:



5. Testing the API
You can now test the API using tools like Postman or cURL.
Create a New User (POST Request)
URL: http://localhost:5000/users
Method: POST
Body (JSON):
jsonCopy code{
"name": "John Doe",
"email": "john.doe@example.com"
}
Get All Users (GET Request)
URL: http://localhost:5000/users
Method: GET
Update a User (PUT Request)
URL: http://localhost:5000/users/1
Method: PUT
Body (JSON):
jsonCopy code{
"name": "John Doe Updated",
"email": "john.doe.updated@example.com"
}
Delete a User (DELETE Request)
URL: http://localhost:5000/users/1
Method: DELETE
Ceated a simple Flask API integrated with SQLAlchemy for handling database operations. We demonstrated how to perform basic CRUD (Create, Read, Update, Delete) operations and tested the API using HTTP requests. By using Flask and SQLAlchemy, you can easily build scalable and efficient web applications that interact with relational databases.
from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy # Initialize the Flask app and configure the database URI app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite' # SQLite Database app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # Disable modification tracking # Initialize SQLAlchemy db = SQLAlchemy(app) # Create a model (database table) class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) def repr(self): return f"<User {self.name}>" # Initialize the database with app.app_context(): db.create_all() # Route to test if the API is working @app.route('/') def home(): return "Welcome to Flask API with SQLAlchemy!" if name == "__main__": app.run(debug=True) file name
The file name for your Flask application can be anything you'd like, but it is common to name it something descriptive of the application. For this example, you could name the file:
app.py
Or, if you'd prefer something more specific, like reflecting the use of SQLAlchemy, you could name it:
flask_sqlalchemy_app.py
After saving the file, you can run it with the following command:
python app.py
Make sure you're in the same directory as the app.py file or specify the full path to the file when running the command.