February 24, 2026

API CRUD en Python con Flask y cliente JS

Creación de una alta, baja, modificación y consulta de una tabla con flask, para poder se leída por web

#pip install flask
#pip install mysql-connector-python
#ejecutar  flask run
from flask import Flask, request, jsonify
import mysql.connector

app = Flask(__name__)


@app.after_request
def add_cors_headers(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
    return response

@app.route("/")
def hello_world():
    return "<p>¡Hola! Flask está funcionando.</p>"




# Configuración de la base de datos (XAMPP)
db_config = {
    'host': 'localhost',
    'user': 'root',
    'password': '',
    'database': 'test'
}


def get_db_connection():
    return mysql.connector.connect(**db_config)


# 1. CONSULTA TODOS
@app.route('/usuarios', methods=['GET'])
def get_usuarios():
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)  # dictionary=True para que devuelva JSON clave-valor
    cursor.execute("SELECT * FROM usuarios")
    usuarios = cursor.fetchall()
    cursor.close()
    conn.close()
    return jsonify(usuarios)


# 2. CONSULTA UNO SOLO
@app.route('/usuarios/<int:id>', methods=['GET'])
def get_usuario(id):
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)
    cursor.execute("SELECT * FROM usuarios WHERE id = %s", (id,))
    usuario = cursor.fetchone()
    cursor.close()
    conn.close()
    if usuario:
        return jsonify(usuario)
    return jsonify({"error": "Usuario no encontrado"}), 404


# 3. ALTA (POST)
@app.route('/usuarios', methods=['POST'])
def add_usuario():
    data = request.get_json()
    nombre = data.get('nombre')
    edad = data.get('edad')

    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("INSERT INTO usuarios (nombre, edad) VALUES (%s, %s)", (nombre, edad))
    conn.commit()
    cursor.close()
    conn.close()
    return jsonify({"message": "Usuario creado"}), 201


# 4. MODIFICACIÓN (PUT)
@app.route('/usuarios/<int:id>', methods=['PUT'])
def update_usuario(id):
    data = request.get_json()
    nombre = data.get('nombre')
    edad = data.get('edad')

    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("UPDATE usuarios SET nombre = %s, edad = %s WHERE id = %s", (nombre, edad, id))
    conn.commit()
    cursor.close()
    conn.close()
    return jsonify({"message": "Usuario actualizado"})


# 5. BAJA (DELETE)
@app.route('/usuarios/<int:id>', methods=['DELETE'])
def delete_usuario(id):
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("DELETE FROM usuarios WHERE id = %s", (id,))
    conn.commit()
    cursor.close()
    conn.close()
    return jsonify({"message": "Usuario eliminado"})


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

Consulta

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <table>
        <thead>
            <tr>
                <th>id</th>
                <th>nombre</th>
                <th>edad</th>
            </tr>
        </thead>
        <tbody id="usuarios-body"></tbody>
    </table>

    <script>
        function cargarUsuarios() {
            fetch('http://127.0.0.1:5000/usuarios')
                .then(respuesta => respuesta.json())
                .then(usuarios => mostrarUsuarios(usuarios))
                .catch(error => console.error(error));
        }
        function mostrarUsuarios(usuarios) {

            const tbody = document.getElementById('usuarios-body');
            tbody.innerHTML = '';
            
            usuarios.forEach((usuario) => {
                const fila = document.createElement('tr');

                const celdaId = document.createElement('td');
                celdaId.textContent = usuario.id;

                const celdaNombre = document.createElement('td');
                celdaNombre.textContent = usuario.nombre;

                const celdaEdad = document.createElement('td');
                celdaEdad.textContent = usuario.edad;

                fila.appendChild(celdaId);
                fila.appendChild(celdaNombre);
                fila.appendChild(celdaEdad);
                tbody.appendChild(fila);
            });
        }
        cargarUsuarios();
    </script>
</body>

</html>

Alta

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Alta</title>
</head>

<body>
    <label>nombre
        <input type="text" id="nombre">
    </label>
    <label>edad
        <input type="text" id="edad">
    </label>
    <button onclick="alta()">Alta</button>

    <script>
        function alta() {
            const nombre = document.getElementById("nombre").value;
            const edad = document.getElementById("edad").value;

            fetch('http://127.0.0.1:5000/usuarios', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    nombre: nombre,
                    edad: edad
                })
            })
                .then((respuesta) => {
                    if (!respuesta.ok) {
                        throw new Error('Error al crear usuario');
                    }
                    return respuesta.json();
                })
                .then((data) => {
                    console.log(data);
                })
                .catch((error) => {
                    console.log(error);
                });
        }
    </script>
</body>

</html>

Leave a Reply

Your email address will not be published. Required fields are marked *