The before code shows the client calling multiple services directly, increasing complexity and network calls. The after code shows the client calling a single API Gateway endpoint, which aggregates data from multiple services and returns a combined response, simplifying the client logic.
### Before: Client calls multiple services directly
import requests
def get_user_profile(user_id):
user_resp = requests.get(f'http://user-service/users/{user_id}')
orders_resp = requests.get(f'http://order-service/orders?user={user_id}')
return {
'user': user_resp.json(),
'orders': orders_resp.json()
}
### After: Client calls API Gateway once
import requests
def get_user_profile(user_id):
resp = requests.get(f'http://api-gateway/profile/{user_id}')
return resp.json()
# API Gateway routing example (simplified)
from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
@app.route('/profile/<user_id>')
def profile(user_id):
# Authentication and rate limiting would happen here
user_resp = requests.get(f'http://user-service/users/{user_id}')
orders_resp = requests.get(f'http://order-service/orders?user={user_id}')
combined = {
'user': user_resp.json(),
'orders': orders_resp.json()
}
return jsonify(combined)