简体   繁体   中英

Calling REST API of a Flask app from another Flask app

I'm running two Flask apps (A & B) on my local machine. In Flask app B, I'm calling an endpoint from Flask app A.

The endpoint being called from Flask app A is: /hello_world

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route("/hello_world", methods=["POST"])
def hello_world():
     a = request.json.get("a")
     b = request.json.get("b")
     return jsonify({a:b})

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=5000,debug=True)

In flask app B, the endpoint /hi_world is making a call to the above endpoint as follows:

import requests
from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route("/hi_world", methods=["POST"])
def hi_world():
     a = request.json.get("a")
     b = request.json.get("b")
     paras = {"a":a, "b":b}
     response = requests.post(url="http://0.0.0.0:5000/",data=paras)
     print(response)
     return None

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=5002,debug=True)

I use postman to make a POST call to the /hi_world where I pass the following dictionary in the request body {"a":"Hello","b":"World"} . However, I get a <Response [404]> . When I call the /hello_world directly from postman it works just fine with a <Response [200]> . What am I doing wrong?

In your second application you need to updated this line:

response = requests.post(url="http://0.0.0.0:5000/",data=paras)

to refer the full URL of the first application, like::

response = requests.post(url="http://0.0.0.0:5000/hello_world",data=paras)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM