AW Dev Rethought

🌟 The best way to predict the future is to invent it - Alan Kay

🧩 Python Automation Recipes – 🌐 API Data Aggregator


Description:

📌 Introduction

Many workflows rely on data from multiple sources — weather, APIs, services, metrics, etc.

But manually checking each source is inefficient and error-prone.

This automation recipe shows how to fetch data from multiple APIs and combine it into a single report using Python.

It’s a foundational pattern for dashboards, monitoring tools, and reporting pipelines.


🔎 Explanation

  • The script sends requests to multiple APIs.
  • It extracts key fields from each response.
  • All data is combined into a single structured report (dictionary or text output).
  • The result can be:
    • printed
    • saved to a file
    • emailed
    • or fed into another system

This example uses:

  • Weather API (wttr.in)
  • Bitcoin price API (CoinDesk)

You can easily replace or extend with your own APIs.


✅ Key Takeaways

  • 🌐 Fetch and combine data from multiple APIs.
  • 📊 Build simple aggregated reports automatically.
  • ⚙️ Great foundation for dashboards and automation pipelines.

Code Snippet:

import requests
from datetime import datetime
from pathlib import Path

# --- Step 1: Configuration ---

CITY = "Bangalore"  # Change as needed
OUTPUT_FILE = Path("api_report.txt")

# --- Step 2: Fetch Weather Data ---
def get_weather(city):
    url = f"https://wttr.in/{city}?format=j1"
    response = requests.get(url, timeout=10)
    data = response.json()

    current = data["current_condition"][0]

    return {
        "temperature": current["temp_C"],
        "feels_like": current["FeelsLikeC"],
        "condition": current["weatherDesc"][0]["value"]
    }

# --- Step 3: Fetch Crypto Data ---
def get_bitcoin_price():
    url = "https://api.coindesk.com/v1/bpi/currentprice.json"
    response = requests.get(url, timeout=10)
    data = response.json()

    return {
        "price_usd": data["bpi"]["USD"]["rate"]
    }

# --- Step 4: Combine Data ---
try:
    weather = get_weather(CITY)
    btc = get_bitcoin_price()

    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    report = f"""
📊 API Aggregated Report
------------------------
Time: {timestamp}

🌤️ Weather in {CITY}:
- Temperature: {weather['temperature']}°C
- Feels Like: {weather['feels_like']}°C
- Condition: {weather['condition']}

₿ Bitcoin Price:
- USD: ${btc['price_usd']}
"""

    print(report)

    # --- Step 5: Save Report ---
    with OUTPUT_FILE.open("w") as f:
        f.write(report)

    print(f"Report saved to: {OUTPUT_FILE}")

except Exception as e:
    print("Failed to fetch API data:", e)

Link copied!

Comments

Add Your Comment

Comment Added!