40 lines
1.0 KiB
Python
40 lines
1.0 KiB
Python
from flask import Flask, jsonify, request
|
|
|
|
app = Flask(__name__)
|
|
|
|
BOOKS = []
|
|
|
|
@app.route('/books', methods=['GET'])
|
|
def get_books():
|
|
return jsonify(BOOKS)
|
|
|
|
@app.route('/books/<int:id>', methods=['GET'])
|
|
def get_book(id):
|
|
book = next((book for book in BOOKS if book['id'] == id), None)
|
|
if book:
|
|
return jsonify(book)
|
|
return jsonify({"message": "Book not found"}), 404
|
|
|
|
@app.route('/books', methods=['POST'])
|
|
def create_book():
|
|
new_book = request.get_json()
|
|
BOOKS.append(new_book)
|
|
return jsonify(new_book), 201
|
|
|
|
@app.route('/books/<int:id>', methods=['PUT'])
|
|
def update_book(id):
|
|
book = next((book for book in BOOKS if book['id'] == id), None)
|
|
if book:
|
|
book.update(request.get_json())
|
|
return jsonify(book)
|
|
return jsonify({"message": "Book not found"}), 404
|
|
|
|
@app.route('/books/<int:id>', methods=['DELETE'])
|
|
def delete_book(id):
|
|
global BOOKS
|
|
BOOKS = [book for book in BOOKS if book['id'] != id]
|
|
return '', 204
|
|
|
|
if __name__ == '__main__':
|
|
app.run(host='0.0.0.0', port=5000)
|