Home > Uncategorized > Python Flask REST API with SQLAlchemy

Python Flask REST API with SQLAlchemy

# Building a Python Flask REST API with SQLAlchemy

Flask is a lightweight web framework for Python, ideal for building RESTful APIs. When paired with SQLAlchemy, a powerful object-relational mapper (ORM), Flask provides a robust platform for managing database interactions. This article will guide you through creating a REST API using Flask and SQLAlchemy, with practical examples and code snippets.

## What is Flask?

Flask is a micro-framework for Python that is widely used for creating web applications. It is lightweight and modular, making it perfect for developing REST APIs. Flask provides essential tools like routing, request handling, and response generation.

## What is SQLAlchemy?

SQLAlchemy is an ORM that allows developers to interact with databases using Python objects rather than raw SQL queries. It supports multiple database backends and enables efficient database management.

## Setting Up the Environment

To begin, ensure you have Python installed on your system. You can install Flask and SQLAlchemy using `pip`.

pip install flask sqlalchemy flask-sqlalchemy

## Creating the Flask App

Start by creating a basic Flask application. We’ll set up the directory structure as follows:

“`
flask_rest_api/
├── app.py
├── models.py
├── config.py
└── requirements.txt
“`

### 1. Configuration File (`config.py`)

The `config.py` file will hold the application configuration, including the database connection string.

class Config:
    SQLALCHEMY_DATABASE_URI = 'sqlite:///example.db'
    SQLALCHEMY_TRACK_MODIFICATIONS = False

### 2. Models File (`models.py`)

This file defines the database models using SQLAlchemy.

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    email = db.Column(db.String(100), unique=True, nullable=False)

    def __repr__(self):
        return f'<user {self.name}="">'

### 3. Main Application File (`app.py`)

This file contains the Flask application setup and API routes.

#### Importing Dependencies and Initializing the App

from flask import Flask, jsonify, request
from config import Config
from models import db, User

app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)

#### Creating the Database

To create the database, use the following snippet:

@app.before_first_request
def create_tables():
    db.create_all()

## REST API Endpoints

### 1. Create a New User

This endpoint allows you to add a new user to the database.

@app.route('/users', methods=['POST'])
def create_user():
    data = request.json
    new_user = User(name=data['name'], email=data['email'])
    db.session.add(new_user)
    db.session.commit()
    return jsonify({'message': 'User created successfully!', 'user': {'name': new_user.name, 'email': new_user.email}})

### 2. Get All Users

This endpoint retrieves all users from the database.

@app.route('/users', methods=['GET'])
def get_users():
    users = User.query.all()
    users_list = [{'id': user.id, 'name': user.name, 'email': user.email} for user in users]
    return jsonify(users_list)

### 3. Get User by ID

Retrieve a specific user using their ID.

@app.route('/users/<int:id>', methods=['GET'])
def get_user(id):
    user = User.query.get_or_404(id)
    return jsonify({'id': user.id, 'name': user.name, 'email': user.email})

### 4. Update User

Update a user’s information based on their ID.

@app.route('/users/<int:id>', methods=['PUT'])
def update_user(id):
    data = request.json
    user = User.query.get_or_404(id)
    user.name = data['name']
    user.email = data['email']
    db.session.commit()
    return jsonify({'message': 'User updated successfully!', 'user': {'name': user.name, 'email': user.email}})

### 5. Delete User

Remove a user from the database.

@app.route('/users/<int:id>', methods=['DELETE'])
def delete_user(id):
    user = User.query.get_or_404(id)
    db.session.delete(user)
    db.session.commit()
    return jsonify({'message': 'User deleted successfully!'})

## Testing the API

To test the API, you can use tools like Postman or `curl`. Here’s an example of how to test the “Create User” endpoint using `curl`:

curl -X POST -H "Content-Type: application/json" -d '{"name": "John Doe", "email": "[email protected]"}' http://127.0.0.1:5000/users

## Running the Application

Start the Flask server by executing the `app.py` file.

python app.py

Visit `http://127.0.0.1:5000` in your browser or use an API testing tool to interact with the endpoints.

## Conclusion

Flask and SQLAlchemy make it simple and efficient to build REST APIs with database support. By following the steps above, you can set up a functional API and extend it to suit your application’s requirements.

Python Flask REST API, SQLAlchemy tutorial, Flask CRUD example, Python database integration, REST API development, Flask SQLAlchemy basics, Python web development