This simple Python application works similarly to the one we created in Add NWS Weather to Your Website JavaScript guide. This is handy if we need to grab weather data as part of another Python application or if we wanted to use it as the base for a more powerful weather application.
Our Requirements
Before we get started, you will need to install the Requests HTTP library for Python. The Requests library allows us to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to URLs or to form-encode POST data.
pip install requests
Let’s Get Started
As with its JavaScript equivalent, we will be passing the latitude and longitude of the location that we want to retrieve the weather data from to the get_weather function. The data will then be extracted from the JSON data object and outputted to the terminal.
#!/usr/bin/python3 import requests from requests.exceptions import HTTPError def get_weather(lat, lng): # Build the `payload` for the requested data. payload = { 'lat': lat, 'lon': lng, 'unit': 0, 'lg': 'english', 'FcstType': 'json' } # Set the `url` variable with the weather link. url = 'https://forecast.weather.gov/MapClick.php' try: # Send a GET request to retrieve the JSON data. response = requests.get(url, params=payload) # Check for HTTP errors before processing. response.raise_for_status() # Return the JSON object of the response. json = response.json() # Print out the values from the JSON data object. print("Location:", json['location']['areaDescription']) print("Temperature:", json['currentobservation']['Temp'] + "°") print("Wind:", json['currentobservation']['Winds'], "mph") print("Humidity:", json['currentobservation']['Relh'] + "%") print("Dew Point:", json['currentobservation']['Dewp'] + "°") print("Barometer:", json['currentobservation']['SLP'], "in") print("Visibility:", json['currentobservation']['Visibility'], "mi") print("Forecast:", json['data']['text'][0]) except HTTPError as http_err: print("HTTP Error Occurred:", http_err) except Exception as err: print("An Exception Occured:", err) if __name__ == "__main__": # Call the 'get_weather' function and pass the latitude and logitude for # the location that we want to retrieve the weather information from. get_weather("38.349819", "-81.632622")
Terminal Output:
Location: Charleston WV
Temperature: 69°
Wind: 3 mph
Humidity: 96%
Dew Point: 68°
Barometer: 30.13 in
Visibility: 10.00 mi
Forecast: Areas of fog after 4am. Otherwise, mostly clear, with a low around 66. Calm wind.
Helpful Tip
There is a lot more weather information available within the JSON data object than is used for this basic project. You can output the entire JSON data object to your terminal or visit the NWS JSON file to see what data is available to use.
#!/usr/bin/python3 import requests from requests.exceptions import HTTPError def get_weather(lat, lng): # Build the `payload` for the requested data. payload = { 'lat': lat, 'lon': lng, 'unit': 0, 'lg': 'english', 'FcstType': 'json' } # Set the `url` variable with the weather link. url = 'https://forecast.weather.gov/MapClick.php' try: # Send a GET request to retrieve the JSON data. response = requests.get(url, params=payload) # Check for HTTP errors before processing. response.raise_for_status() # Return the JSON object of the response. json = response.json() # Print all JSON data to terminal. print(json) except HTTPError as http_err: print("HTTP Error Occurred:", http_err) except Exception as err: print("An Exception Occured:", err) if __name__ == "__main__": # Call the 'get_weather' function and pass the latitude and logitude for # the location that we want to retrieve the weather information from. get_weather("38.349819", "-81.632622")