-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
285875d
commit 5c6a877
Showing
2 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
from flask import Flask, request, jsonify | ||
|
||
app = Flask(__name__) | ||
|
||
# Sample data | ||
books = [ | ||
{"id": 1, "title": "Book 1", "author": "Author 1"}, | ||
{"id": 2, "title": "Book 2", "author": "Author 2"}, | ||
{"id": 3, "title": "Book 3", "author": "Author 3"} | ||
] | ||
|
||
# Route to get all books | ||
@app.route('/books', methods=['GET']) | ||
def get_books(): | ||
return jsonify(books) | ||
|
||
# Route to get a specific book by its ID | ||
@app.route('/books/<int:book_id>', methods=['GET']) | ||
def get_book(book_id): | ||
for book in books: | ||
if book['id'] == book_id: | ||
return jsonify(book) | ||
return jsonify({'error': 'Book not found'}), 404 | ||
|
||
# Route to add a new book | ||
@app.route('/books', methods=['POST']) | ||
def add_book(): | ||
new_book = request.json | ||
books.append(new_book) | ||
return jsonify(new_book), 201 | ||
|
||
# Route to update an existing book | ||
@app.route('/books/<int:book_id>', methods=['PUT']) | ||
def update_book(book_id): | ||
for book in books: | ||
if book['id'] == book_id: | ||
book.update(request.json) | ||
return jsonify(book) | ||
return jsonify({'error': 'Book not found'}), 404 | ||
|
||
# Route to delete a book | ||
@app.route('/books/<int:book_id>', methods=['DELETE']) | ||
def delete_book(book_id): | ||
for i, book in enumerate(books): | ||
if book['id'] == book_id: | ||
del books[i] | ||
return jsonify({'message': 'Book deleted'}) | ||
return jsonify({'error': 'Book not found'}), 404 | ||
|
||
if __name__ == '__main__': | ||
app.run(debug=True) |