from flask import Flask,request,jsonify
app=Flask(__name__)
books=[
{'id':1,'title':'book1','author':'au1'},
{'id':2,'title':'book2','author':'au2'},
{'id':3,'title':'book3','author':'au3'},
{'id':4,'title':'book4','author':'au4'}
]
#獲取所有圖書
@app.route('/books',methods=['GET'])
def get_books():
return jsonify(books)
#新增一本圖書
@app.route('/books',methods=['POST'])
def add_book():
new_book=request.get_json()
new_book['id']=len(books)+1 #id是基於列表長度的
books.append(new_book)
return jsonify(new_book),201
#根據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
#更新圖書資訊
@app.route('/books/<int:book_id>',methods=['PUT'])
def update_book(book_id):
update_book=request.get_json()
for i,book in enumerate(books):
if book['id']==book_id:
books[i]=update_book;
return jsonify(update_book);
return jsonify({'error':"book not found"}),404
#刪除圖書
@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 '',204
return jsonify({'error':'book not found'}),404
if __name__=='__main__':
app.run(debug=True)