0
0
FlaskHow-ToBeginner · 4 min read

How to Create a CRUD API in Flask: Simple Guide

To create a CRUD API in Flask, define routes for each operation: create (POST), read (GET), update (PUT), and delete (DELETE). Use Flask's routing decorators and handle JSON data to build endpoints that manage resources.
📐

Syntax

In Flask, you create API endpoints using route decorators like @app.route(). Each route corresponds to a URL and HTTP method (GET, POST, PUT, DELETE) for CRUD operations.

  • POST: Create new data
  • GET: Read or retrieve data
  • PUT: Update existing data
  • DELETE: Remove data

Use request.get_json() to get JSON data from client requests and jsonify() to send JSON responses.

python
from flask import Flask, request, jsonify

app = Flask(__name__)

# Create (POST)
@app.route('/items', methods=['POST'])
def create_item():
    data = request.get_json()
    # logic to add item
    return jsonify({'message': 'Item created', 'item': data}), 201

# Read (GET)
@app.route('/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
    # logic to get item by id
    return jsonify({'item_id': item_id, 'name': 'Sample Item'})

# Update (PUT)
@app.route('/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
    data = request.get_json()
    # logic to update item
    return jsonify({'message': 'Item updated', 'item_id': item_id, 'new_data': data})

# Delete (DELETE)
@app.route('/items/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
    # logic to delete item
    return jsonify({'message': 'Item deleted', 'item_id': item_id})
💻

Example

This example shows a simple in-memory CRUD API for managing items using Flask. It stores items in a dictionary and supports creating, reading, updating, and deleting items via HTTP requests.

python
from flask import Flask, request, jsonify

app = Flask(__name__)

items = {}
next_id = 1

@app.route('/items', methods=['POST'])
def create_item():
    global next_id
    data = request.get_json()
    item = {'id': next_id, 'name': data.get('name')}
    items[next_id] = item
    next_id += 1
    return jsonify(item), 201

@app.route('/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
    item = items.get(item_id)
    if item:
        return jsonify(item)
    return jsonify({'error': 'Item not found'}), 404

@app.route('/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
    item = items.get(item_id)
    if not item:
        return jsonify({'error': 'Item not found'}), 404
    data = request.get_json()
    item['name'] = data.get('name', item['name'])
    return jsonify(item)

@app.route('/items/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
    if item_id in items:
        del items[item_id]
        return jsonify({'message': 'Item deleted'})
    return jsonify({'error': 'Item not found'}), 404

if __name__ == '__main__':
    app.run(debug=True)
Output
Running Flask app on http://127.0.0.1:5000/ with endpoints: POST /items GET /items/<item_id> PUT /items/<item_id> DELETE /items/<item_id>
⚠️

Common Pitfalls

  • Not specifying HTTP methods in @app.route() causes routes to accept only GET by default.
  • Forgetting to parse JSON with request.get_json() leads to errors when accessing data.
  • Not handling missing or invalid data can cause server errors.
  • Using global variables without proper care can cause concurrency issues in real apps.
  • Not returning proper HTTP status codes reduces API clarity.
python
from flask import Flask, request, jsonify

app = Flask(__name__)

# Wrong: No methods specified, only GET allowed
@app.route('/items')
def create_item_wrong():
    data = request.get_json()  # Will fail on POST
    return jsonify(data)

# Right: Specify POST method
@app.route('/items', methods=['POST'])
def create_item_right():
    data = request.get_json()
    if not data or 'name' not in data:
        return jsonify({'error': 'Name is required'}), 400
    return jsonify({'message': 'Item created', 'item': data}), 201
📊

Quick Reference

Use this quick guide for Flask CRUD API routes:

OperationHTTP MethodRoute ExamplePurpose
CreatePOST/itemsAdd a new item
ReadGET/items/Get item details
UpdatePUT/items/Modify existing item
DeleteDELETE/items/Remove an item

Key Takeaways

Define routes with correct HTTP methods for each CRUD operation in Flask.
Use request.get_json() to read JSON data and jsonify() to send JSON responses.
Handle missing data and errors gracefully with proper HTTP status codes.
Avoid global state for data storage in production; use databases instead.
Test each endpoint with tools like curl or Postman to verify behavior.