Hello requests
#
# hello_requests.py
#
# Installation: 'requests' in requirements.txt
import requests
# The `requests` library allows you to send HTTP requests, for
# accessing web pages or web APIs.
# https://requests.readthedocs.io
# Weather API documentation
# https://www.weather.gov/documentation/services-web-api
# National Weather Service (NWS)
# https://www.weather.gov/
# NOAA
# https://www.noaa.gov/
def main():
# https://api.weather.gov/points/{latitude},{longitude}
= "https://api.weather.gov/points/34.0699142,-118.3294098"
url
# Use the `get()` function to retrieve a webpage (GET request).
= requests.get(url)
response
# Status code 200 is success.
print("status_code:", response.status_code)
print()
if response.status_code != 200:
print("Error.")
return
# The response from a webpage will generatlly be HTML. The
# response from a web API will usually be in JSON format, which
# you can think of as a bunch of nested dictionaries.
= response.json()
result_json = result_json['properties']
properties
= properties['relativeLocation']['properties']['city']
city = properties['forecast']
forecast_url
print("city:", city)
print("forecast_url:", forecast_url)
print()
# Accessing the actual forecast requires a second GET request.
= requests.get(forecast_url)
response
= response.json()['properties']
properties = properties['periods']
periods
for period in periods:
print(period['name'])
print(period['detailedForecast'])
print()
if __name__ == '__main__':
main()
Output:
status_code: 200
city: West Hollywood
forecast_url: https://api.weather.gov/gridpoints/LOX/152,46/forecast
This Afternoon
Mostly sunny, with a high near 86. Southwest wind around 10 mph.
Tonight
A slight chance of rain showers between 11pm and 5am. Partly
cloudy, with a low around 66. Southwest wind 0 to 10 mph. Chance of
precipitation is 20%.
Wednesday
Mostly sunny, with a high near 82. Southwest wind 0 to 10 mph.
Wednesday Night
Patchy fog after 11pm. Mostly cloudy, with a low around 63. South
southwest wind 0 to 10 mph.
Thursday
Patchy fog before 11am. Mostly sunny, with a high near 78. South
southwest wind 0 to 10 mph.
Thursday Night
Patchy fog after 11pm. Partly cloudy, with a low around 64.
Friday
Patchy fog before 11am. Mostly sunny, with a high near 77.
Friday Night
Patchy fog after 11pm. Partly cloudy, with a low around 64.
Saturday
Patchy fog before 11am. Mostly sunny, with a high near 76.
Saturday Night
Patchy fog after 11pm. Partly cloudy, with a low around 63.
Sunday
Patchy fog before 11am. Mostly sunny, with a high near 79.
Sunday Night
Patchy fog after 11pm. Partly cloudy, with a low around 65.
Monday
Patchy fog before 11am. Mostly sunny, with a high near 82.
Monday Night
Clear, with a low around 65.