我正在编写 api1,需要获取从 api2 到 api1 的回调,我将从 api2 获得响应,这个 api2 响应我将在 api1 中使用,我该怎么做..?
我正在 python 中尝试这个,所以我需要在 api1 for 循环中获取 api2 响应,不确定当我使用 api1 时如何从 api2 获得响应。
如果我正确理解了问题,那么你可以尝试这种方法:
api1
将向 POST
发出 api2
请求。
api2
将处理请求并发回响应 api1
。
然后,api1
将在后续处理中使用 api2
的响应。
一些示例代码:
## api2.py:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/api2_endpoint', methods=['POST'])
def api2_endpoint():
data = request.get_json()
# Process the data (but just echoing it back for this example)
return jsonify({'message': 'Response from API2', 'data': data})
if __name__ == '__main__':
app.run(port=5001)
## api1.py:
import requests
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api1_endpoint', methods=['GET'])
def api1_endpoint():
# Data you want to send to api2
data = {"key": "value"}
response = requests.post('http://localhost:5001/api2_endpoint', json=data)
api2_response = response.json()
# Use api2_response in api1 processing
# For this example, let's just send it back as the response for api1
return jsonify(api2_response)
if __name__ == '__main__':
app.run(port=5000)
然后按照以下步骤操作