快速建立API服務使用 flask,要先安裝
先執行 python -m pip install flask
然後寫個 app.py 檔案
上代碼! 如下:
from flask import Flask, request, jsonify
import time, random
app = Flask(__name__)
bookStoreList = [
{"id": 1, "name": "PYTHON_DEV", "price": 100, "count":10},
{"id": 2, "name": "JAVA_DEV", "price": 200, "count":20},
{"id": 3, "name": "GOLANG_DEV", "price": 300, "count":30},
{"id": 3, "name": "C#_DEV", "price": 400, "count":40}
]
def _find_next_id():
return max(book["id"] for book in bookStoreList) + 1
def _find_book(name):
result = list(filter(lambda data: data.get('name')==name, bookStoreList))
if len(result) > 0 :
return {'success':True,'bookinfo':result[0]}
else :
return {'success':False,'bookinfo':None}
@app.get("/bookstore/getbooks")
def get_books():
return jsonify(bookStoreList)
@app.post("/bookstore/buybook")
def buy_book():
if request.is_json:
bookinfo = request.get_json()
print('bookinfo: ', bookinfo)
# 隨機API耗費時間 1~10s
time.sleep(random.randrange(1,10))
return jsonify(_find_book(bookinfo["BookName"])), 201
return {"error": "Request must be JSON"}, 415
@app.post("/bookstore/addbook")
def add_book():
if request.is_json:
newbookinfo = request.get_json()
newbookinfo["id"] = _find_next_id()
bookStoreList.append(newbookinfo)
return newbookinfo, 201
return {"error": "Request must be JSON"}, 415
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8321)
完成後直接執行 python app,便可以看到以下資訊
代表API服務已經成功啟動,然後就可以開始做測試,
這邊我自己啟動的port是 8321,這個可自行調整
改 app.run(host="0.0.0.0", port=8321) 這個就行了
裡面有幾隻API其中一支的 curl 如下
curl --location --request POST 'http://127.0.0.1:8321/bookstore/buybook' \
--header 'Content-Type: application/json' \
--data-raw '{
"BookName":"PYTHON_DEV"
}'
另外為了給第一篇做測試,/bookstore/buybook 裡面有加 隨機API耗費時間,
大概就這樣,Cheer !