Fetch weather API mock and write dashboard HTML in Python
This script fetches a mock weather API response as a Python dict, builds a simple HTML dashboard, writes it to a file, and prints both the file path and JSON payload.
Python code
45 linesfrom datetime import datetime
import json
import os
def fetch_weather_mock(city: str) -> dict:
"""Return a mock weather payload for a given city."""
return {
"city": city,
"temperature_c": 21.5,
"condition": "Partly Cloudy",
"humidity": 58,
"wind_kph": 12.3,
"updated_at": datetime.utcnow().isoformat() + "Z",
}
def build_dashboard_html(data: dict) -> str:
"""Build a simple weather dashboard HTML page from the data."""
return f"""<!DOCTYPE html>
<html>
<head><title>Weather - {data['city']}</title></head>
<body>
<h1>Weather Dashboard</h1>
<h2>{data['city']}</h2>
<p><strong>Temperature:</strong> {data['temperature_c']}°C</p>
<p><strong>Condition:</strong> {data['condition']}</p>
<p><strong>Humidity:</strong> {data['humidity']}%</p>
<p><strong>Wind:</strong> {data['wind_kph']} km/h</p>
<p><small>Last updated: {data['updated_at']}</small></p>
</body>
</html>"""
if __name__ == "__main__":
city = "Berlin"
weather = fetch_weather_mock(city)
html = build_dashboard_html(weather)
output_path = "weather_dashboard.html"
with open(output_path, "w", encoding="utf-8") as f:
f.write(html)
print(f"Dashboard written to {os.path.abspath(output_path)}")
print(json.dumps(weather, indent=2))
Output
Dashboard written to /path/to/your/working/directory/weather_dashboard.html
{
"city": "Berlin",
"temperature_c": 21.5,
"condition": "Partly Cloudy",
"humidity": 58,
"wind_kph": 12.3,
"updated_at": "2025-01-01T12:34:56.789012Z"
}
How it works
The fetch_weather_mock function returns a dictionary mimicking a real weather API response, using datetime.utcnow().isoformat() + "Z" to generate a UTC timestamp in ISO 8601 format with a Z suffix (common in API payloads). The build_dashboard_html function uses an f-string to interpolate the city, temperature, condition, humidity, wind, and timestamp into a clean HTML structure. After generating the HTML string, the code writes it to a file using open with UTF-8 encoding to safely handle special characters like the degree symbol. The script then prints the absolute path to confirm the file was created and dumps the weather data as pretty-printed JSON for inspection.
Common mistakes
- Using `datetime.utcnow()` which is deprecated in Python 3.12+; prefer `datetime.now(timezone.utc)` for timezone-aware timestamps.
- Assuming the mock data structure matches a real API response — always validate field names and types when integrating a real endpoint.
- Forgetting to close the file when manually writing — using a `with` block is safer and more idiomatic.
Variations
- Use `requests.get()` to fetch real API data instead of the mock function, then pass the JSON response to `build_dashboard_html`.
- Template the HTML using Jinja2 for more complex dashboards with loops, conditionals, and reusable components.
Real-world use cases
- Scheduled jobs that generate a static HTML status page from API data and deploy it to a CDN or web server.
- Automated reporting scripts that pull current conditions from a weather API and email an HTML digest to stakeholders.
- Local monitoring tools that fetch metrics from internal services and write a self-contained HTML dashboard for quick manual inspection.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.