How to create a simple CRUD application with Flask

How to Create a Simple CRUD Application with Flask

Flask is a lightweight and flexible web framework for Python that allows developers to build web applications quickly and efficiently. When developing web applications, CRUD (Create, Read, Update, Delete) operations are fundamental for managing data. In this article, we will guide you through creating a simple CRUD application using Flask, providing you with clear code examples and step-by-step instructions.

What is a CRUD Application?

A CRUD application is designed to handle data management operations effectively. Each letter in the acronym stands for:

  • Create: Add new data entries.
  • Read: Retrieve existing data.
  • Update: Modify existing data entries.
  • Delete: Remove data entries.

These operations form the backbone of most web applications, from content management systems to e-commerce sites.

Use Cases for CRUD Applications

CRUD applications can be used in various scenarios, including:

  • Task management systems: Track tasks and their statuses.
  • User management systems: Manage user accounts and profiles.
  • Inventory management: Keep track of stock levels and product details.

Prerequisites

Before we start, ensure you have the following:

  • Python installed on your machine.
  • Flask and Flask-SQLAlchemy installed. You can install them using pip:
pip install Flask Flask-SQLAlchemy

Setting Up Your Flask Application

Step 1: Create Your Project Structure

Create a new directory for your project and navigate into it:

mkdir flask_crud_app
cd flask_crud_app

Inside this directory, create a file named app.py where your application code will reside.

Step 2: Initialize the Flask App

Open app.py and add the following code to set up your Flask application and configure the database:

from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

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), nullable=True)

db.create_all()

Step 3: Creating CRUD Operations

Now, let's implement the CRUD functionalities.

Create Operation

To add a new item, create a route that accepts POST requests:

@app.route('/items', methods=['POST'])
def create_item():
    data = request.get_json()
    new_item = Item(name=data['name'], description=data.get('description'))
    db.session.add(new_item)
    db.session.commit()
    return jsonify({'id': new_item.id}), 201

Read Operation

To retrieve all items, create a route for GET requests:

@app.route('/items', methods=['GET'])
def get_items():
    items = Item.query.all()
    return jsonify([{ 'id': item.id, 'name': item.name, 'description': item.description } for item in items])

To read a specific item, add another route:

@app.route('/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
    item = Item.query.get_or_404(item_id)
    return jsonify({'id': item.id, 'name': item.name, 'description': item.description})

Update Operation

For updating an item, add a route for PUT requests:

@app.route('/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
    item = Item.query.get_or_404(item_id)
    data = request.get_json()
    item.name = data['name']
    item.description = data.get('description')
    db.session.commit()
    return jsonify({'id': item.id, 'name': item.name, 'description': item.description})

Delete Operation

To delete an item, implement the DELETE route:

@app.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'}), 204

Step 4: Running the Application

At the bottom of your app.py, add the following code to run your application:

if __name__ == '__main__':
    app.run(debug=True)

Now, you can run the application:

python app.py

Step 5: Testing Your CRUD Application

You can test the CRUD operations using tools like Postman or cURL. Here are some example requests:

  • Create an Item:
  • POST /items json { "name": "Sample Item", "description": "This is a sample item." }

  • Get All Items:

  • GET /items

  • Update an Item:

  • PUT /items/1 json { "name": "Updated Item", "description": "Updated description." }

  • Delete an Item:

  • DELETE /items/1

Conclusion

Congratulations! You've successfully created a simple CRUD application using Flask. By following this guide, you now have a solid understanding of how to perform essential data management operations in a web application.

Key Takeaways

  • Flask is an excellent choice for building web applications due to its simplicity and flexibility.
  • CRUD operations are fundamental to managing data effectively.
  • Testing your API with tools like Postman can streamline the development process.

With this knowledge, you can expand your application further by adding user authentication, error handling, or even deploying it to a web server. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.