Group Part II: Data Modeling and Visualization

Q8: Interacting with Web APIs Problem Statement: Analyzing Weather Data from OpenWeatherMap API Dataset: Weather data retrieved from OpenWeatherMap API Description: The goal is to interact with the OpenWeatherMap API to retrieve weather data for a specific location and perform data modeling and visualization to analyze weather patterns over time. Tasks to Perform: 1. Register and obtain an API key from OpenWeatherMap. 2. Interact with the OpenWeatherMap API using the API key to retrieve weather data for a specific location. 3. Extract relevant weather attributes such as temperature, humidity, wind speed, and precipitation from the API response. 4. Clean and preprocess the retrieved data, handling missing values or inconsistent formats. 5. Perform data modeling to analyze weather patterns, such as calculating average temperature, maximum/minimum values, or trends over time. 6. Visualize the weather data using appropriate plots, such as line charts, bar plots, or scatter plots, to represent temperature changes, precipitation levels, or wind speed variations. 7. Apply data aggregation techniques to summarize weather statistics by specific time periods (e.g., daily, monthly, seasonal). 8. Incorporate geographical information, if available, to create maps or geospatial visualizations representing weather patterns across different locations. 9. Explore and visualize relationships between weather attributes, such as temperature and humidity, using correlation plots or heatmaps.

Interacting with Web APIs

Solution and implementation for Q8 from Data Modeling & Visualization (dmv).

8_openweathermap_api.ipynb Download

DMV 2 – Weather API (Data Collection and Visualization)

Code Cell 1
import requests
import pandas as pd
import matplotlib.pyplot as plt
Code Cell 2
key = "YOUR_API_KEY"
city = "Pune"
url = f"https://api.openweathermap.org/data/2.5/forecast?q={city}&appid={key}&units=metric"
Code Cell 3
data = requests.get(url).json()
Code Cell 4
df = pd.DataFrame([{
    "Date": x["dt_txt"],
    "Temperature": x["main"]["temp"],
    "Humidity": x["main"]["humidity"],
    "Wind": x["wind"]["speed"]
} for x in data["list"]])
Code Cell 5
print(df.head())
print("Average Temperature:", df["Temperature"].mean())
print("Maximum Temperature:", df["Temperature"].max())
print("Minimum Temperature:", df["Temperature"].min())
                  Date  Temperature  Humidity  Wind
0  2025-04-01 00:00:00         22.9        66   2.3
1  2025-04-01 03:00:00         27.9        55   5.0
2  2025-04-01 06:00:00         30.2        52   3.5
3  2025-04-01 09:00:00         26.9        54   2.0
4  2025-04-01 12:00:00         25.3        73   4.7
Average Temperature: 24.8275
Maximum Temperature: 30.2
Minimum Temperature: 18.6
Code Cell 6
df.plot(x="Date", y="Temperature", kind="line", title="Temperature Forecast")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Cell 6 output
<Figure size ...>
Code Cell 7
df.plot(x="Date", y="Humidity", kind="bar", title="Humidity Forecast")
plt.tight_layout()
plt.show()
Cell 7 output
<Figure size ...>
Code Cell 8
df.plot(x="Temperature", y="Humidity", kind="scatter", title="Temperature vs Humidity")
plt.show()
Cell 8 output
<Figure size ...>
Code Cell 9
# Save to HTML file
import folium

city_coord = [data["city"]["coord"]["lat"], data["city"]["coord"]["lon"]]
m = folium.Map(location=city_coord)
folium.Marker(city_coord, popup=city).add_to(m)
m.save("weather_map.html")

df.to_html("weather_data.html", index=False)
print("Saved to weather_map.html and weather_data.html")
Saved to weather_map.html and weather_data.html
weather_map.html Download
<!DOCTYPE html>
<html>
<head>
    
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <script src="https://cdn.jsdelivr.net/npm/leaflet@1.9.3/dist/leaflet.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1.9.3/dist/leaflet.css"/>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css"/>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.2.0/css/all.min.css"/>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css"/>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/python-visualization/folium/folium/templates/leaflet.awesome.rotate.min.css"/>
    
            <meta name="viewport" content="width=device-width,
                initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
            <style>
                #map_c05019a49f9e5215e3f6f4d400c329b8 {
                    position: relative;
                    width: 100.0%;
                    height: 100.0%;
                    left: 0.0%;
                    top: 0.0%;
                }
                .leaflet-container { font-size: 1rem; }
            </style>

            <style>html, body {
                width: 100%;
                height: 100%;
                margin: 0;
                padding: 0;
            }
            </style>

            <style>#map {
                position:absolute;
                top:0;
                bottom:0;
                right:0;
                left:0;
                }
            </style>

            <script>
                L_NO_TOUCH = false;
                L_DISABLE_3D = false;
            </script>

        
</head>
<body>
    
    
            <div class="folium-map" id="map_c05019a49f9e5215e3f6f4d400c329b8" ></div>
        
</body>
<script>
    
    
            var map_c05019a49f9e5215e3f6f4d400c329b8 = L.map(
                "map_c05019a49f9e5215e3f6f4d400c329b8",
                {
                    center: [18.5204, 73.8567],
                    crs: L.CRS.EPSG3857,
                    ...{
  "zoom": 10,
  "zoomControl": true,
  "preferCanvas": false,
}

                }
            );

            

        
    
            var tile_layer_b2e65402dacef3482beb38a299a0f2f2 = L.tileLayer(
                "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
                {
  "minZoom": 0,
  "maxZoom": 19,
  "maxNativeZoom": 19,
  "noWrap": false,
  "attribution": "\u0026copy; \u003ca href=\"https://www.openstreetmap.org/copyright\"\u003eOpenStreetMap\u003c/a\u003e contributors",
  "subdomains": "abc",
  "detectRetina": false,
  "tms": false,
  "opacity": 1,
}

            );
        
    
            tile_layer_b2e65402dacef3482beb38a299a0f2f2.addTo(map_c05019a49f9e5215e3f6f4d400c329b8);
        
    
            var marker_fbf3011be6998e529a3521a820cb2a3b = L.marker(
                [18.5204, 73.8567],
                {
}
            ).addTo(map_c05019a49f9e5215e3f6f4d400c329b8);
        
    
        var popup_aec88686dabbb2dfd63ef064c6e3a574 = L.popup({
  "maxWidth": "100%",
});

        
            
                var html_6437144bf43944a73431c8e7e719c612 = $(`<div id="html_6437144bf43944a73431c8e7e719c612" style="width: 100.0%; height: 100.0%;">Pune</div>`)[0];
                popup_aec88686dabbb2dfd63ef064c6e3a574.setContent(html_6437144bf43944a73431c8e7e719c612);
            
        

        marker_fbf3011be6998e529a3521a820cb2a3b.bindPopup(popup_aec88686dabbb2dfd63ef064c6e3a574)
        ;

        
    
</script>
</html>

Other Questions in Data Modeling & Visualization

See All Available Questions
Download