How to call microservice-2 from microservice-1 using python?

Issue

How to call my microservice-2 from microservice-1. So our result looks like this:-

Result :- {“message”: “vivek”} –> {“message”: “keviv”, “random”: 3.89}

command to access microservice-1:-

curl http://127.0.0.1:5000/reverse_random/vivek

microservice-1

from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/reverse_reandom/<string:string>', methods=['GET'])
def reverse(string):
    string = string[::-1]
    return jsonify({'message': string })


if __name__ == '__main__':
   app.run(debug = True)

microservice-2

import random
from flask import Flask, jsonify

app = Flask(__name__)


@app.route('/', methods=['GET'])
def myRandom():
    r1 = random.uniform(0, 10)
    return jsonify({'message': r1 })

if __name__ == '__main__':
    app.run(debug=True)

Solution

Run microservice-2 on a different port. Send request using Python standard or 3rd party library from microservice-1
to microservice-2 upon request to microservice-1.

Below is the example of using Python3 standard library only:

m1.py:

from flask import Flask, jsonify
import urllib
import json 

app = Flask(__name__)

@app.route('/reverse_random/<string:string>', methods=['GET'])
def reverse(string):
    content = urllib.request.urlopen('http://127.0.0.1:5001').read().decode('utf-8')
    print('response from m2: ', content)
    string = string[::-1]
    return jsonify({'message': string, 'random' : json.loads(content)['message']})


if __name__ == '__main__':
   app.run(debug = True)

m2.py:

import random
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/', methods=['GET'])
def myRandom():
    r1 = random.uniform(0, 10)

    return jsonify({'message': r1 })

if __name__ == '__main__':
    app.run(debug=True, port=5001) # running m2 on a different port than default 5000

Run the m1: python3 m1.py

Run the m2 in a different shell: python3 m2.py

Send request to m1: curl http://127.0.0.1:5000/reverse_random/vivek

The result is:

{ 
  "message": "keviv",  
  "random": 4.138115905045612 
} 

Observe the log of m1 and of m2 to make sure m2 was invoked.

Answered By – rok

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published