Building CRUD APIs with Flask and SQLAlchemy

 Creating a reliable backend API is essential for any fullstack web application. One of the most common requirements is to implement CRUD operations—Create, Read, Update, and Delete—which form the backbone of data management in most systems. In the Python ecosystem, Flask is a lightweight web framework, and SQLAlchemy is a powerful Object Relational Mapper (ORM). Together, they provide an efficient way to build CRUD APIs.

In this blog, we’ll explore how to set up CRUD APIs using Flask and SQLAlchemy step by step.


Why Use Flask with SQLAlchemy?

Flask is minimalistic, letting you add only what you need.

SQLAlchemy simplifies database interaction by allowing you to work with Python objects instead of raw SQL.

Together, they form a flexible and scalable stack for API development.


Setting Up the Environment

First, install the necessary packages:


bash


pip install Flask Flask-SQLAlchemy


1. Initialize Flask and SQLAlchemy

python


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)


2. Create the Data Model

python


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 to_dict(self):

        return {"id": self.id, "name": self.name, "email": self.email}

Initialize the database:

bash


python

>>> from your_app_file import db

>>> db.create_all()


3. Create (POST) a New User

python


@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(new_user.to_dict()), 201


4. Read (GET) All Users

python


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

def get_users():

    users = User.query.all()

    return jsonify([user.to_dict() for user in users])

Read a single user:


python


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

def get_user(user_id):

    user = User.query.get_or_404(user_id)

    return jsonify(user.to_dict())


5. Update (PUT) a User

python


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

def update_user(user_id):

    user = User.query.get_or_404(user_id)

    data = request.get_json()

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

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

    db.session.commit()

    return jsonify(user.to_dict())


6. Delete (DELETE) a User

python


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

def delete_user(user_id):

    user = User.query.get_or_404(user_id)

    db.session.delete(user)

    db.session.commit()

    return jsonify({'message': 'User deleted'})


Conclusion

Building CRUD APIs with Flask and SQLAlchemy is straightforward, efficient, and highly customizable. Flask provides the routing and request-handling capabilities, while SQLAlchemy manages the database layer with ease and flexibility. This combination is perfect for fullstack applications where the backend needs to serve a modern frontend framework like React or Vue.

With this foundation, you can now scale your API, implement validation, authentication, pagination, and even connect it to more powerful databases like PostgreSQL or MySQL. Whether you're building a personal project or an enterprise app, Flask and SQLAlchemy are a solid choice for your backend development.

Learn FullStack Python Training Course

Read More : Flask and OpenAPI: Designing APIs with Swagger for Fullstack Applications

Read More : Fullstack Python: Implementing GraphQL APIs in Flask

Read More : Flask and JWT: Secure API Development with Authentication

Visit Quality Thought Training Institute

Get Direction

Comments

Popular posts from this blog

Tosca vs Selenium: Which One to Choose?

How to Build a Reusable Component Library

Flask API Optimization: Using Content Delivery Networks (CDNs)