Let’s take the weather API from the previous page and create something useful. We’ll get weather data for the past 7 days, analyze it, visualize it, and save it.This brings together everything you’ve learned: APIs, data processing, file handling, and visualization.
import requestsfrom datetime import datetime, timedelta# Calculate datestoday = datetime.now()week_ago = today - timedelta(days=7)# Format dates for API (YYYY-MM-DD)start_date = week_ago.strftime("%Y-%m-%d")end_date = today.strftime("%Y-%m-%d")# Get Paris weather for past weekurl = f"https://api.open-meteo.com/v1/forecast?latitude=48.85&longitude=2.35&start_date={start_date}&end_date={end_date}&daily=temperature_2m_max,temperature_2m_min"response = requests.get(url)data = response.json()print(data)
import matplotlib.pyplot as plt# Create the plotplt.figure(figsize=(10, 6))plt.plot(df['date'], df['max_temp'], marker='o', label='Max Temp')plt.plot(df['date'], df['min_temp'], marker='o', label='Min Temp')# Add labels and titleplt.xlabel('Date')plt.ylabel('Temperature (°C)')plt.title('Paris Weather - Past 7 Days')plt.legend()# Rotate x-axis labels for readabilityplt.xticks(rotation=45)plt.tight_layout()# Save the plotplt.savefig('weather_chart.png')plt.show()
import os# Create data folder if it doesn't existif not os.path.exists('data'): os.makedirs('data')# Save to CSVdf.to_csv('data/paris_weather.csv', index=False)print("Data saved to data/paris_weather.csv")