-
Notifications
You must be signed in to change notification settings - Fork 0
/
flask.txt
51 lines (43 loc) · 1.42 KB
/
flask.txt
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
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)