File size: 1,766 Bytes
007f0f1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
from flask import Flask, jsonify, request
app = Flask(__name__)
# Sample data - you can replace this with your actual data source
books = [
{"id": 1, "title": "Python Programming", "author": "Guido van Rossum"},
{"id": 2, "title": "Flask Basics", "author": "Miguel Grinberg"},
{"id": 3, "title": "Data Science Handbook", "author": "Jake VanderPlas"}
]
# Route to get all books
@app.route('/', methods=['GET'])
def get_books_list():
return jsonify(books)
@app.route('/books', methods=['GET'])
def get_books():
return jsonify(books)
# Route to get a specific book by ID
@app.route('/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
book = next((book for book in books if book['id'] == book_id), None)
if book:
return jsonify(book)
else:
return jsonify({'message': 'Book not found'}), 404
# Route to create a new book
@app.route('/books', methods=['POST'])
def create_book():
new_book = request.get_json()
books.append(new_book)
return jsonify({'message': 'Book created successfully'}), 201
# Route to update a book
@app.route('/books/<int:book_id>', methods=['PUT'])
def update_book(book_id):
book = next((book for book in books if book['id'] == book_id), None)
if not book:
return jsonify({'message': 'Book not found'}), 404
else:
data = request.get_json()
book.update(data)
return jsonify({'message': 'Book updated successfully'})
# Route to delete a book
@app.route('/books/<int:book_id>', methods=['DELETE'])
def delete_book(book_id):
global books
books = [book for book in books if book['id'] != book_id]
return jsonify({'message': 'Book deleted successfully'})
if __name__ == '__main__':
app.run(debug=True)
|