PYTHON

Consolidate Multiple External API Calls into a Single Endpoint

Reduce client-server round-trips by creating a backend endpoint that fetches data from multiple external APIs and aggregates results for a single client request using Python Flask.

from flask import Flask, jsonify
import requests
import asyncio
import aiohttp # Requires: pip install aiohttp

app = Flask(__name__)

# External API URLs
API_URL_1 = 'https://jsonplaceholder.typicode.com/posts/1' # Example API
API_URL_2 = 'https://jsonplaceholder.typicode.com/users/1' # Example API

async def fetch_data(session, url):
    async with session.get(url) as response:
        response.raise_for_status()
        return await response.json()

async def fetch_all_data():
    async with aiohttp.ClientSession() as session:
        tasks = [
            fetch_data(session, API_URL_1),
            fetch_data(session, API_URL_2),
        ]
        results = await asyncio.gather(*tasks)
        return {
            'post_data': results[0],
            'user_data': results[1]
        }

@app.route('/aggregated-data', methods=['GET'])
def aggregated_data():
    try:
        # asyncio.run() is typically used to run the top-level entry point
        # for an async program. In a web framework like Flask, it's safer to
        # use a library like 'flask-executor' or 'asyncio.to_thread' if Flask
        # is not running with an ASGI server, or ensure your Flask app is
        # async-compatible (e.g., Quart).
        # For simplicity in this snippet, we use asyncio.run.
        # In a production Flask app, consider proper async integration.
        data = asyncio.run(fetch_all_data())
        return jsonify(data)
    except requests.exceptions.RequestException as e:
        return jsonify({'error': str(e)}), 500
    except Exception as e:
        return jsonify({'error': 'An unexpected error occurred'}), 500

if __name__ == '__main__':
    # Note: For production use with Flask, consider a WSGI server
    # that supports async, or offload async tasks to a worker process.
    # 'pip install aiohttp' is required for this snippet.
    app.run(debug=True, port=3001)
How it works: This Python Flask snippet demonstrates how to create a single backend endpoint that aggregates data from multiple external APIs. Instead of the client making separate requests, it makes one call to `/aggregated-data`. The Flask server then uses `asyncio` and `aiohttp` to concurrently fetch data from `API_URL_1` and `API_URL_2`. Once all external responses are received, they are combined into a single JSON object and returned to the client. This pattern reduces network overhead and simplifies client-side data fetching logic.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs