• Python Snacks
  • Posts
  • A guide on using the National Weather Service API with Python

A guide on using the National Weather Service API with Python

The National Weather Service (NWS) provides an API that allows developers to access a wide range of weather data, from forecasts to historical observations.

Before diving into the code, there’s a few things to remember:

  1. Review the NWS API documentation to understand its structure and available endpoints.

  2. Remember that the base endpoint for this API is https://api.weather.gov. All endpoints use this base URL for all requests.

  3. You must pass in the User Agent field into your request, which can be anything (name of application, email, etc). However, this should be unique to your application.

» Note: The NWS API is RESTful, meaning it responds to HTTP requests and returns data in JSON format. However, the data is in GeoJSON format, given the inclusion of geometry data.

Let’s suppose you want to fetch a listing of all alerts. By using the /alerts endpoint, we can retrieve a listing of this. you can also filter by passing in a parameter, such as the state parameter:

https://api.weather.gov/alerts?area={state}

Now, integrating it with Python, you’re going to want to use the requests package. A stripped down version of what this looks like without error handling, etc may be something such as:

import requests

headers = {'User-Agent' : 'myapp'}
endpoint = 'https://api.weather.gov/alerts?area={state}'

response = requests.get(endpoint, headers = headers)
data = response.json()

# `features` contains the data we want.
print(data['features']) 

Or maybe we want something that includes more robust error handling. This could look something like this:

import requests
from requests.exceptions import HTTPError, Timeout, RequestException

def make_nws_request(endpoint, user_agent):
    headers = {
        "User-Agent": user_agent,
    }

    try:
        response = requests.get(
                       endpoint, 
                       headers=headers
                   )
        # Raise HTTPError for bad responses (4xx or 5xx)
        response.raise_for_status()
        return response.json()

    except HTTPError as http_err:
        print(f"HTTP error occurred: {http_err} - Status code: {response.status_code}")
    except Timeout as timeout_err:
        print(f"Request timed out: {timeout_err}")
    except RequestException as req_err:
        print(f"Request error: {req_err}")
    
    return None  # Return None if an error occurred


if __name__ == "__main__":
    # Sample user agent
    user_agent = "MyWeatherApp/1.0"

    BASE_URL = "https://api.weather.gov"
    
    # Example 1: Get forecast for a specific location
    lat, lon = 39.7456, -97.0892
    forecast_url = f"{BASE_URL}/points/{lat},{lon}"
    data = make_nws_request(forecast_url, user_agent)
    
    if data:
        print(data)
    else:
        print("Failed to retrieve data.")

Note that each endpoint does contain different data. Review the NWS API documentation to learn more about each endpoint and be ready to spend some time with it.

» By the way, I built NWSApy, which is a python wrapper for this API, making requests easy.

Happy coding!

📧 Join the Python Snacks Newsletter! 🐍

Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:

  1. Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.

  2. Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.

  3. Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.

You can unsubscribe at any time.

Interested in starting a newsletter or a blog?

Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.

If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.

This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.

Reply

or to participate.