Here's a simple Python snippet that uses the requests library to check the current weather for a given location using the National Weather Service (NWS) API:
import requests
def get_current_weather(location):
# NWS API endpoint
api_url = f"https://api.weather.gov/points/{location}"
try:
# Send GET request to the API
response = requests.get(api_url)
response.raise_for_status() # Raise an exception for 4xx or 5xx status codes
# Parse the JSON response
data = response.json()
# Extract the forecast URL from the response
forecast_url = data["properties"]["forecast"]
# Send GET request to the forecast URL
forecast_response = requests.get(forecast_url)
forecast_response.raise_for_status()
# Parse the JSON response
forecast_data = forecast_response.json()
# Extract the current weather conditions
current_weather = forecast_data["properties"]["periods"][0]["detailedForecast"]
return current_weather
except requests.exceptions.RequestException as e:
print("Error occurred while fetching weather data:", e)
return None
# Example usage
location = "37.7749,-122.4194" # Latitude and longitude of the location (e.g., San Francisco)
weather = get_current_weather(location)
if weather:
print("Current weather:", weather)
else:
print("Failed to retrieve current weather.")
This code does the following:
-
We define a function called get_current_weather that takes a location parameter representing the latitude and longitude of the desired location.
-
We construct the API URL using the provided location coordinates.
-
We send a GET request to the API URL using requests.get() and handle any exceptions that may occur.
-
If the request is successful, we parse the JSON response using response.json().
-
From the response data, we extract the forecast URL.
-
We send another GET request to the forecast URL to retrieve the detailed weather forecast.
-
We parse the forecast JSON response and extract the current weather conditions from the first period in the forecast data.
-
We return the current weather conditions.
-
In the example usage, we provide the latitude and longitude of a location (e.g., San Francisco) and call the get_current_weather function.
-
If the weather data is successfully retrieved, we print the current weather conditions. Otherwise, we print an error message.
Note: Make sure to install the requests library by running pip install requests before running this code.
Keep in mind that you need to replace the location variable with the actual latitude and longitude coordinates of the desired location.