Python – Weather Report for any City
There is a similar article to this in which the weather report is obtained using Excel Vba code. To use this open weathermap Api , you have to first register with your email and get the AppId key.
They provide a free limited subscription. Refer the official website to know more about the pricing & limitations in free Apikay.
- Once you get the Apikey, enter the API key in the below link
- Get valid city name from this JSON file.
Once the above details are ready, then the below code will get the Current weather report for the City entered as input.
# Current Weather Report for City import requests # <-- To query Weather API Server import json # <-- To parse Weather JSON Data # Register with Openweathermap & Get APPID apiAppid = "appid=" + "" # Get City name from User weatherCity = input("Get Weather For City : ") weatherCity = "&q=" + weatherCity # Weather Reporting Metrics Unit # "&units=imperial" # <-- To get Temperature Unit in Farenheit # "&units=metric" # <-- To get Temperature Unit in Celcius weatherUnit = "&units=metric" # Finally to build the URL & query API weatherApiurl = "http://api.openweathermap.org/data/2.5/weather?" weatherApiurl = weatherApiurl + apiAppid + weatherCity + weatherUnit response = requests.get(weatherApiurl) weatherJsonData = response.json() # Check Return Code from API Server & Proceed if weatherJsonData["cod"] == "404": print("Error Code = " + weatherJsonData["cod"]) else: # Print Basic Weather Parameters print("Description = " + weatherJsonData["weather"][0]["description"]) print("Temperatur = " + str(weatherJsonData["main"]["temp"])) print("Pressure = " + str(weatherJsonData["main"]["pressure"])) print("Humidity = " + str(weatherJsonData["main"]["humidity"]))
The JSON file returned from the API will look something similar to this one. So, the other parameters related to the weather report can be parsed further by customizing the above Python code.
{ "message": "accurate", "cod": "200", "count": 1, "list": [ { "id": 2643743, "name": "London", "coord": { "lat": 51.5085, "lon": -0.1258 }, "main": { "temp": 7, "pressure": 1012, "humidity": 81, "temp_min": 5, "temp_max": 8 }, "dt": 1485791400, "wind": { "speed": 4.6, "deg": 90 }, "sys": { "country": "GB" }, "rain": null, "snow": null, "clouds": { "all": 90 }, "weather": [ { "id": 701, "main": "Mist", "description": "mist", "icon": "50d" }, { "id": 300, "main": "Drizzle", "description": "light intensity drizzle", "icon": "09d" } ] } ] }