DEV Community

Manthan Ankolekar
Manthan Ankolekar

Posted on • Edited on

6

Building a CRUD Application with Flask and SQLAlchemy

In this blog, we'll walk through building a simple CRUD (Create, Read, Update, Delete) API using Flask and SQLAlchemy. This guide will cover setting up the project, configuring the database, defining models, creating routes, and running the application.

Prerequisites

Before getting started, ensure you have the following installed:

  • Python 3.x
  • Flask
  • Flask-SQLAlchemy
  • Flask-Migrate

Project Setup

1. Clone the Repository

git clone https://github.com/manthanank/crud-flask-sqlalchemy.git
cd crud-flask
Enter fullscreen mode Exit fullscreen mode

2. Create a Virtual Environment

python -m venv venv
source venv/bin/activate  # On Windows: `venv\Scripts\activate`
Enter fullscreen mode Exit fullscreen mode

3. Install Dependencies

pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

Database Configuration

We are using Flask-SQLAlchemy for ORM and Flask-Migrate for database migrations. The database configuration is stored in app/config.py:

import os
from dotenv import load_dotenv

load_dotenv()

class Config:
    SQLALCHEMY_DATABASE_URI = os.getenv("DATABASE_URL", "sqlite:///app.db")
    SQLALCHEMY_TRACK_MODIFICATIONS = False
Enter fullscreen mode Exit fullscreen mode

Initializing the Database

To set up the database, run the following commands:

flask db init
flask db migrate -m "Initial migration"
flask db upgrade
Enter fullscreen mode Exit fullscreen mode

On Windows, before running these commands, set the environment variable:

set FLASK_APP=run.py
Enter fullscreen mode Exit fullscreen mode

Defining the Model

We define a simple Item model in app/models.py:

from app import db

class Item(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    description = db.Column(db.String(200))

    def to_dict(self):
        return {"id": self.id, "name": self.name, "description": self.description}
Enter fullscreen mode Exit fullscreen mode

Creating the API Routes

In app/routes.py, we define the API endpoints for CRUD operations using Flask’s Blueprints:

1. Create an Item

@api_bp.route("/items", methods=["POST"])
def create_item():
    data = request.json
    new_item = Item(name=data["name"], description=data.get("description"))
    db.session.add(new_item)
    db.session.commit()
    return jsonify(new_item.to_dict()), 201
Enter fullscreen mode Exit fullscreen mode

2. Retrieve All Items

@api_bp.route("/items", methods=["GET"])
def get_items():
    items = Item.query.all()
    return jsonify([item.to_dict() for item in items])
Enter fullscreen mode Exit fullscreen mode

3. Retrieve a Single Item

@api_bp.route("/items/<int:item_id>", methods=["GET"])
def get_item(item_id):
    item = Item.query.get_or_404(item_id)
    return jsonify(item.to_dict())
Enter fullscreen mode Exit fullscreen mode

4. Update an Item

@api_bp.route("/items/<int:item_id>", methods=["PUT"])
def update_item(item_id):
    item = Item.query.get_or_404(item_id)
    data = request.json
    item.name = data.get("name", item.name)
    item.description = data.get("description", item.description)
    db.session.commit()
    return jsonify(item.to_dict())
Enter fullscreen mode Exit fullscreen mode

5. Delete an Item

@api_bp.route("/items/<int:item_id>", methods=["DELETE"])
def delete_item(item_id):
    item = Item.query.get_or_404(item_id)
    db.session.delete(item)
    db.session.commit()
    return jsonify({"message": "Item deleted successfully"})
Enter fullscreen mode Exit fullscreen mode

Setup Environment Variables

.env

DATABASE_URL=sqlite:///app.db
Enter fullscreen mode Exit fullscreen mode

Running the Application

Run the Flask application with:

python run.py
Enter fullscreen mode Exit fullscreen mode

The API will be accessible at http://127.0.0.1:5000/api/items.

API Endpoints

Method Endpoint Description
POST /api/items Create a new item
GET /api/items Get all items
GET /api/items/<id> Get a single item
PUT /api/items/<id> Update an item
DELETE /api/items/<id> Delete an item

Testing the API

You can test the API using Postman or cURL.

  • Create an Item:
  curl -X POST http://127.0.0.1:5000/api/items -H "Content-Type: application/json" -d '{"name": "Laptop", "description": "Gaming laptop"}'
Enter fullscreen mode Exit fullscreen mode
  • Get All Items:
  curl -X GET http://127.0.0.1:5000/api/items
Enter fullscreen mode Exit fullscreen mode
  • Get a Specific Item:
  curl -X GET http://127.0.0.1:5000/api/items/1
Enter fullscreen mode Exit fullscreen mode
  • Update an Item:
  curl -X PUT http://127.0.0.1:5000/api/items/1 -H "Content-Type: application/json" -d '{"name": "Updated Laptop", "description": "High-performance gaming laptop"}'
Enter fullscreen mode Exit fullscreen mode
  • Delete an Item:
  curl -X DELETE http://127.0.0.1:5000/api/items/1
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this guide, we built a Flask CRUD API using SQLAlchemy for database operations and Flask-Migrate for migrations. This setup provides a solid foundation for building RESTful services in Flask.

🎉 Congratulations! You’ve built a Flask CRUD API with SQLAlchemy. 🚀

Happy coding! 🚀

Exploring the Code

Visit the GitHub repository to explore the code in detail.


Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (1)

ACI image

ACI.dev: Fully Open-source AI Agent Tool-Use Infra (Composio Alternative)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Check out our GitHub!

Join the Runner H "AI Agent Prompting" Challenge: $10,000 in Prizes for 20 Winners!

Runner H is the AI agent you can delegate all your boring and repetitive tasks to - an autonomous agent that can use any tools you give it and complete full tasks from a single prompt.

Check out the challenge

DEV is bringing live events to the community. Dismiss if you're not interested. ❤️