Sobes.tech
Intern
205

What is CRUD?

Answer from AI

sobes.tech AI

CRUD is an acronym that represents the basic operations performed on data in most information systems, especially in the context of working with databases and APIs.

Decoding:

  • Create - The operation of adding new data to the storage.
  • Read - The operation of retrieving data from the storage.
  • Update - The operation of modifying existing data in the storage.
  • Delete - The operation of removing data from the storage.

Examples of implementation in Python:

Interacting with a database (e.g., SQLite using sqlite3):

# Create
import sqlite3
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('Alice', 30))
conn.commit()

# Read
cursor.execute("SELECT * FROM users WHERE name = ?", ('Alice',))
user = cursor.fetchone()
print(user)

# Update
cursor.execute("UPDATE users SET age = ? WHERE name = ?", (31, 'Alice'))
conn.commit()

# Delete
cursor.execute("DELETE FROM users WHERE name = ?", ('Alice',))
conn.commit()

conn.close()

RESTful API in Flask:

# Create (POST /users)
from flask import Flask, request, jsonify
app = Flask(__name__)

users = [] # Example in-memory storage

@app.route('/users', methods=['POST'])
def create_user():
    new_user = request.json
    users.append(new_user)
    return jsonify(new_user), 201

# Read (GET /users, GET /users/<id>)
@app.route('/users', methods=['GET'])
def get_users():
    return jsonify(users)

@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    if user_id < len(users):
        return jsonify(users[user_id])
    return jsonify({"error": "User not found"}), 404

# Update (PUT /users/<id>)
@app.route('/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
    if user_id < len(users):
        users[user_id].update(request.json)
        return jsonify(users[user_id])
    return jsonify({"error": "User not found"}), 404

# Delete (DELETE /users/<id>)
@app.route('/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    if user_id < len(users):
        deleted_user = users.pop(user_id)
        return jsonify(deleted_user)
    return jsonify({"error": "User not found"}), 404

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

CRUD is a fundamental set of operations that underpins data interaction in most software systems and is often used for designing APIs and database interfaces.