# 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), 201Exemple de JSON à envoyer avec Postman :
{
"title": "Dracula",
"author": "Bram Stoker"
}# 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é', 404Exemple de JSON à envoyer avec Postman :
{
"title": "Dracula",
"author": "Bram Stoker"
}# 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