在Flask中實現RESTful API可以通過以下步驟:
from flask import Flask
app = Flask(__name__)
@app.route('/api/resource', methods=['GET'])
def get_resource():
# 處理GET請求
pass
@app.route('/api/resource', methods=['POST'])
def create_resource():
# 處理POST請求
pass
@app.route('/api/resource/<int:id>', methods=['PUT'])
def update_resource(id):
# 處理PUT請求
pass
@app.route('/api/resource/<int:id>', methods=['DELETE'])
def delete_resource(id):
# 處理DELETE請求
pass
from flask import request
@app.route('/api/resource', methods=['POST'])
def create_resource():
data = request.json
# 處理POST請求中的json數據
pass
from flask import jsonify
@app.route('/api/resource', methods=['GET'])
def get_resource():
data = {'key': 'value'}
return jsonify(data)
if __name__ == '__main__':
app.run()
通過以上步驟,您可以在Flask中實現一個簡單的RESTful API。您還可以使用Flask-RESTful等擴展庫來更方便地創建RESTful API。