How to create a simple CRUD application in Python

How to Create a Simple CRUD Application in Python

Creating a CRUD (Create, Read, Update, Delete) application is one of the foundational skills for any aspiring developer. CRUD applications are ubiquitous in web development and are essential for managing data in various applications. In this article, we’ll walk through how to create a simple CRUD application in Python using Flask, a lightweight web framework that's perfect for beginners.

What is CRUD?

CRUD stands for:

  • Create: Add new data to your database.
  • Read: Retrieve and display existing data.
  • Update: Modify existing data.
  • Delete: Remove data from your database.

These four operations form the backbone of most database-driven applications, making them crucial for developers to understand.

Why Use Python and Flask for CRUD Applications?

Python is a versatile programming language known for its readability and simplicity, making it an excellent choice for web development. Flask, being a micro-framework, allows developers to build applications quickly without the overhead of more complex frameworks. Together, they provide a powerful yet straightforward environment for creating CRUD applications.

Prerequisites

Before we dive into the code, ensure you have the following:

  • Python 3.x installed on your system.
  • Basic understanding of Python and HTML.
  • Familiarity with command-line operations.

Setting Up Your Environment

  1. Install Flask: First, you need to install Flask. You can do this using pip:

bash pip install Flask

  1. Create Your Project Directory: Create a new directory for your project and navigate into it:

bash mkdir flask_crud_app cd flask_crud_app

  1. Create Your Application File: Create a file named app.py:

bash touch app.py

Building the CRUD Application

Step 1: Import Necessary Libraries

Open app.py and import the required libraries:

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

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

Step 2: Define Your Model

Next, define a model that represents the data structure. For this example, we'll create a simple Item model.

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

    def __repr__(self):
        return f"<Item {self.name}>"

Step 3: Initialize the Database

Before running the application, create the database. You can add the following code at the bottom of your app.py:

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

Step 4: Implement CRUD Operations

Now, let’s implement the CRUD operations.

Create

Create a new item using a POST request.

@app.route('/item', methods=['POST'])
def add_item():
    data = request.get_json()
    new_item = Item(name=data['name'])
    db.session.add(new_item)
    db.session.commit()
    return jsonify({"message": "Item created!"}), 201

Read

Retrieve the list of items.

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

Update

Update an existing item.

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

Delete

Delete an item.

@app.route('/item/<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!"}), 200

Step 5: Run Your Application

Finally, add this code to the bottom of your app.py to run your Flask application:

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

You can start your application by running:

python app.py

Testing Your CRUD Application

You can test your CRUD operations using a tool like Postman or cURL.

  • Create an Item:
  • Method: POST
  • URL: http://127.0.0.1:5000/item
  • Body: {"name": "Sample Item"}

  • Read Items:

  • Method: GET
  • URL: http://127.0.0.1:5000/items

  • Update an Item:

  • Method: PUT
  • URL: http://127.0.0.1:5000/item/1
  • Body: {"name": "Updated Item"}

  • Delete an Item:

  • Method: DELETE
  • URL: http://127.0.0.1:5000/item/1

Conclusion

Congratulations! You've created a simple CRUD application using Python and Flask. This foundational project can be expanded with more features, such as user authentication, frontend frameworks, or even deployment to a cloud platform.

By mastering CRUD operations, you’re well on your way to becoming a proficient developer. Keep experimenting, and soon you’ll be able to take on more complex projects with confidence!

SR
Syed
Rizwan

About the Author

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