範例如下: #!/bin/python3
# 載入Flask套件
from flask import Flask
# 創建Flask app物件
app = Flask(__name__)
# 創建 output 範例內容
output = [
{
"pid": "1",
"title": "Example01",
"price": 10,
"img": "https://picsum.photos/id/999/1200/600",
"isAvailable": True
},
{
"id": "2",
"title": "Example02",
"price": 60,
"img": "https://picsum.photos/id/1070/1200/600",
"isAvailable": True
}
]
# 建立products路由,回傳 output,及狀態 200
@app.route("/products")
def products():
return {"products": {"Message": "Get all products..", "output": output}}, 200
if __name__ == "__main__":
app.run(port=8088, debug=True)
至瀏覽器輸入 http://127.0.0.1:8080/products
3. 使用flask_restful封裝API
#!/bin/python3
# 載入Flask套件
from flask import Flask
# 載入Flask RestFul 套件
from flask_restful import Api, Resource
# 創建Flask app物件
app = Flask(__name__)
# 創建Flask api物件
api = Api(app)
# 創建 output 範例內容
output = [
{
"pid": "1",
"title": "Example01",
"price": 10,
"img": "https://picsum.photos/id/999/1200/600",
"isAvailable": True
},
{
"id": "2",
"title": "Example02",
"price": 60,
"img": "https://picsum.photos/id/1070/1200/600",
"isAvailable": True
}
]
# 創建Products 物件並繼承Resource物件
class Products(Resource):
def get(self):
return {"products": {"Message": "Get all products..", "output": output}}, 200
# 建立API路由products,並將該路由導向Products物件
api.add_resource(Products, '/products')
if __name__ == "__main__":
app.run(port=8088, debug=True)
至瀏覽器輸入執行 127.0.0.1:8088/products
其實作法很單純,建立一個EndPoint路由。
並將要輸出的資料或內容擺入,
接下來使用者就可以取得相關資料,
不過上述得介紹都只是簡單的GET方法,
那我們要如何去做新增刪除及修改呢???
請看下一章節囉~~~~