Building microservices in Python

Building microservices in Python involves creating small, independent services that can communicate with each other. Below, I'll provide a simple example using Flask for the web framework and Redis for inter-service communication. This example will consist of two microservices: one for user data and another for order data.

pip install Flask
pip install redis
         

Create a user service (user_service.py):

  from flask import Flask, jsonify
import redis

app = Flask(__name__)
redis_client = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)

@app.route('/user/<int:user_id>', methods=['GET'])
def get_user(user_id):
    user_data = redis_client.hgetall(f'user:{user_id}')
    if user_data:
        return jsonify(user_data)
    else:
        return jsonify({'error': 'User not found'}), 404

if __name__ == '__main__':
    app.run(port=5001)
        

Create an order service (order_service.py):

from flask import Flask, jsonify
import redis

app = Flask(__name__)
redis_client = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)

@app.route('/order/<int:order_id>', methods=['GET'])
def get_order(order_id):
    order_data = redis_client.hgetall(f'order:{order_id}')
    if order_data:
        return jsonify(order_data)
    else:
        return jsonify({'error': 'Order not found'}), 404

if __name__ == '__main__':
    app.run(port=5002)
        

Run the services:

python user_service.py
python order_service.py
python app.py
        

Now, you can access user and order information through the main application by making requests to http://localhost:5000/get_user_info/<user_id> and http://localhost:5000/get_order_info/<order_id>, respectively.

Note: This example uses Redis as a simple in-memory data store for illustration purposes. In a real-world scenario, you would likely use a more robust database and implement additional features such as error handling, authentication, and more.

Follow me at Medium to get more Interesting Articles -Prasad – Medium




To view or add a comment, sign in

More articles by Venkatesh Prasad S

  • Thread VS Process in Python

    In Python processing, both threads and processes are used to achieve concurrency and parallelism in executing tasks…

Explore content categories