National Weather Service REST API with Python

  • 00:00 Intro
  • 00:53 Why National Weather Service API matters
  • 08:28 National Weather Service API Basic Information
  • 14:42 Getting Weather Alerts with State and parsing JSON Response
  • 21:30 Weather data with Lat and Lon from GeoIP API
  • 31:42 Final Thoughts

1-state.py

This code retrieves alerts about a state and then prints them to the screen.

Using the JSON module you can format the JSON response into a “pretty” format so that its easier to understand when printed to the screen.

import requests
import json

state = "FL"

response = requests.get(f'https://api.weather.gov/alerts/active?area={state}').json()

#print(response)

#response_pretty = json.dumps(response, indent=2)

#print(response_pretty)

for x in response['features']:
  print(x['properties']['areaDesc'])
  print(x['properties']['headline'])
  print(x['properties']['description'])
  print('\n******\n')

2-lat-lon.py

This script finds you latitude and longitude based on your external IP Address, and then writes weather alerts to an alert.html file as a web page.

import requests

ip_address = requests.get('http://api.ipify.org').text

print(ip_address)

geo_data = requests.get(f'http://ip-api.com/json/{ip_address}').json()

print(geo_data)

lat = geo_data['lat']
lon = geo_data['lon']

print(lat)
print(lon)

response = requests.get(f'https://api.weather.gov/alerts?point={lat},{lon}').json()

print(f"Alerts: {len(response['features'])}")

file = open('alert.html', 'w')
for x in response['features']:
  file.write(f"<h1>{x['properties']['headline']}</h1>")
  file.write(f"<h3>{x['properties']['areaDesc']}</h3>")
  file.write(f"<p>{x['properties']['description']}</p>")
file.close()

Be the first to comment

Leave a Reply