Skip to content

Instantly share code, notes, and snippets.

@bastienapp
Created May 12, 2026 14:27
Show Gist options
  • Select an option

  • Save bastienapp/d62e0012acf3d30da5ee46db18e9bc1b to your computer and use it in GitHub Desktop.

Select an option

Save bastienapp/d62e0012acf3d30da5ee46db18e9bc1b to your computer and use it in GitHub Desktop.
CRUD Flask PostgreSQL

Create - POST

# Création d'un livre
@app.route('/books', methods=['POST'])
def add_book():
    data = request.get_json()

    title = data['title']
    author = data['author']

    connection = get_connection()
    cursor = connection.cursor()

    cursor.execute(
        'INSERT INTO book (title, author) VALUES (%s, %s) RETURNING *',
        (title, author)
    )

    book = cursor.fetchone()

    connection.commit()

    cursor.close()
    connection.close()

    return jsonify(book), 201

Exemple de JSON à envoyer avec Postman :

{
  "title": "Dracula",
  "author": "Bram Stoker"
}

Update - PUT

# Mise à jour d'un livre
@app.route('/books/<int:id>', methods=['PUT'])
def update_book(id):
    data = request.get_json()

    title = data['title']
    author = data['author']

    connection = get_connection()
    cursor = connection.cursor()

    cursor.execute(
        'UPDATE book SET title = %s, author = %s WHERE book_id = %s RETURNING *',
        (title, author, id)
    )

    book = cursor.fetchone()

    connection.commit()

    cursor.close()
    connection.close()

    if book:
        return jsonify(book), 200
    else:
        return 'Livre non trouvé', 404

Exemple de JSON à envoyer avec Postman :

{
  "title": "Dracula",
  "author": "Bram Stoker"
}

Delete - DELETE

# Suppression d'un livre
@app.route('/books/<int:id>', methods=['DELETE'])
def delete_book(id):
    connection = get_connection()
    cursor = connection.cursor()

    cursor.execute(
        'DELETE FROM book WHERE book_id = %s RETURNING *',
        (id,)
    )

    book = cursor.fetchone()

    connection.commit()

    cursor.close()
    connection.close()

    if book:
        return 'Livre supprimé', 200
    else:
        return 'Livre non trouvé', 404
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment