0
0
Flaskframework~5 mins

CRUD operations in Flask

Choose your learning style9 modes available
Introduction

CRUD operations let you create, read, update, and delete data in a web app. They help manage information easily.

Building a simple blog where users can add, edit, or remove posts.
Creating a contact list app to add, view, update, or delete contacts.
Making a to-do list where tasks can be added, marked done, or removed.
Developing a product catalog where items can be managed by an admin.
Syntax
Flask
from flask import Flask, request, jsonify

app = Flask(__name__)

# Create
@app.route('/items', methods=['POST'])
def create_item():
    # code to add item
    pass

# Read
@app.route('/items', methods=['GET'])
def get_items():
    # code to get items
    pass

# Update
@app.route('/items/<int:id>', methods=['PUT'])
def update_item(id):
    # code to update item
    pass

# Delete
@app.route('/items/<int:id>', methods=['DELETE'])
def delete_item(id):
    # code to delete item
    pass

Each operation uses a different HTTP method: POST for create, GET for read, PUT for update, DELETE for delete.

Routes define the URL paths and accept parameters like item IDs for update and delete.

Examples
This example shows how to add a new item to a list using POST.
Flask
from flask import Flask, request, jsonify

app = Flask(__name__)
items = []

@app.route('/items', methods=['POST'])
def create_item():
    data = request.json
    items.append(data)
    return jsonify(data), 201
This returns all items in JSON format using GET.
Flask
@app.route('/items', methods=['GET'])
def get_items():
    return jsonify(items)
This updates an item by its index if it exists.
Flask
@app.route('/items/<int:id>', methods=['PUT'])
def update_item(id):
    data = request.json
    if 0 <= id < len(items):
        items[id] = data
        return jsonify(data)
    return jsonify({'error': 'Item not found'}), 404
This deletes an item by index and returns it.
Flask
@app.route('/items/<int:id>', methods=['DELETE'])
def delete_item(id):
    if 0 <= id < len(items):
        removed = items.pop(id)
        return jsonify(removed)
    return jsonify({'error': 'Item not found'}), 404
Sample Program

This Flask app lets you add, view, update, and delete items stored in a list. Each route handles one CRUD operation using JSON data.

Flask
from flask import Flask, request, jsonify

app = Flask(__name__)
items = []

@app.route('/items', methods=['POST'])
def create_item():
    data = request.json
    items.append(data)
    return jsonify(data), 201

@app.route('/items', methods=['GET'])
def get_items():
    return jsonify(items)

@app.route('/items/<int:id>', methods=['PUT'])
def update_item(id):
    data = request.json
    if 0 <= id < len(items):
        items[id] = data
        return jsonify(data)
    return jsonify({'error': 'Item not found'}), 404

@app.route('/items/<int:id>', methods=['DELETE'])
def delete_item(id):
    if 0 <= id < len(items):
        removed = items.pop(id)
        return jsonify(removed)
    return jsonify({'error': 'Item not found'}), 404

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

Flask uses decorators (@app.route) to connect URLs to functions.

Use JSON format to send and receive data in APIs.

Remember to handle errors like missing items gracefully.

Summary

CRUD means Create, Read, Update, Delete - basic data actions.

Flask routes use HTTP methods to perform these actions.

JSON is commonly used to exchange data in Flask APIs.