Building CRUD APIs with Flask and SQLAlchemy

Creating a robust and scalable RESTful API is a fundamental task for backend developers. Python’s Flask microframework, when combined with SQLAlchemy (an Object Relational Mapper, or ORM), provides a clean and efficient way to build CRUD (Create, Read, Update, Delete) APIs. In this blog, we’ll walk through how to build a simple CRUD API using Flask and SQLAlchemy.


What You’ll Need

Before we begin, make sure you have the following installed:

Python (3.x)

Flask

Flask-SQLAlchemy

You can install the required packages using pip:


bash

Copy

Edit

pip install Flask Flask-SQLAlchemy

Setting Up the Flask App

Let’s start by creating a basic Flask application:


python

Copy

Edit

from flask import Flask, request, jsonify

from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False


db = SQLAlchemy(app)

We’ve configured Flask to use a SQLite database for simplicity, but SQLAlchemy supports multiple databases like MySQL and PostgreSQL.


Creating the Model

We’ll define a User model with fields id, name, and email.


python

Copy

Edit

class User(db.Model):

    id = db.Column(db.Integer, primary_key=True)

    name = db.Column(db.String(100), nullable=False)

    email = db.Column(db.String(100), unique=True, nullable=False)

Now, initialize the database:


python

Copy

Edit

with app.app_context():

    db.create_all()

Building CRUD Endpoints

Let’s now create routes to perform the basic CRUD operations.


Create a User (POST)

python

Copy

Edit

@app.route('/users', methods=['POST'])

def create_user():

    data = request.get_json()

    new_user = User(name=data['name'], email=data['email'])

    db.session.add(new_user)

    db.session.commit()

    return jsonify({'message': 'User created successfully!'}), 201

Read All Users (GET)

python

Copy

Edit

@app.route('/users', methods=['GET'])

def get_users():

    users = User.query.all()

    return jsonify([{'id': user.id, 'name': user.name, 'email': user.email} for user in users])

Read Single User (GET)

python

Copy

Edit

@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})

Update a User (PUT)

python

Copy

Edit

@app.route('/users/<int:id>', methods=['PUT'])

def update_user(id):

    user = User.query.get_or_404(id)

    data = request.get_json()

    user.name = data.get('name', user.name)

    user.email = data.get('email', user.email)

    db.session.commit()

    return jsonify({'message': 'User updated successfully!'})

Delete a User (DELETE)

python

Copy

Edit

@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!'})

Running the App

Run your Flask app with:


bash

Copy

Edit

python app.py

Make sure your file is named app.py or adjust accordingly.


Conclusion

Building CRUD APIs with Flask and SQLAlchemy is straightforward and powerful. SQLAlchemy’s ORM capabilities abstract the complexity of direct SQL queries, and Flask provides a lightweight structure to build and scale your API. This setup forms a solid foundation for real-world applications, which you can enhance further with authentication, pagination, and input validation.

Learn FullStack Python Training
Read More : Fullstack Python: Implementing GraphQL APIs in Flask

Visit Our IHUB Talent Training Institute in Hyderabad

Comments

Popular posts from this blog

How to Use Tosca's Test Configuration Parameters

Installing Java and Eclipse IDE for Selenium Automation

How Flutter Works Behind the Scenes