When I’m first interacting with an API and I want to
make sense of its responses, sometimes I’ll copy the text
to a text editor and break it down, line by line, to make it
more human-readable. This way I can see the natural
hierarchy of the JSON and figure out exactly what I have
to look for when I’m decoding the response in my code.
It starts with putting the key: value pairs on the individual
lines (example 10-2). Here you can see that there are
keys like “sunriseTime Local”, and “precipChance”, and
“narrative”, which is the verbal description of the
forecast for the coming days of the week.
Keep in mind that not all APIs are created equal and you’ll
have to review their documentation to determine if it’s
the right one for your project. Also, most APIs limit the
number of requests you can make, and some even charge
you to use their services. Many times, the API providers
have a free tier for a small number of daily requests, which
is perfect for experimentation and personal use.
Example 10-1. Partial JSON response from
WeatherUnderground’sAPI
{
"calendarDayTemperatureMax": [74,83,75,73,62,63],
"calendarDayTemperatureMin": [49,55,63,59,52,50],
"dayOfWeek": ["Saturday,"Sunday","Monday","Tuesday",
"Wednesday","Thursday"]
...
"daypart": [
{
"cloudCover": [null,37,38,78,86,65,79,89,92,82,83,61],
"dayOrNight":
[null,"N","D","N","D","N","D","N","D","N","D","N"],
"precipChance": [null,1,1,49,51,24,24,56,55,39,33,2
4],
....
}
]
}
172 Getting Started with Raspberry Pi
GSW_RASPI_4ED_FIN.indd 172GSW_RASPI_4ED_FIN.indd 172 10/28/21 10:54 AM10/28/21 10:54 AM
As it happens, JSON is identical in form to Python’s dictionary data
type (a set of key/value entries), which makes it very easy to write
Python code that reads and writes JSON to interact with various
APIs. To do this, you can import Python’s json library.
If you would like to really get a sense of what the API offers, you can
make some commands in your terminal:
$ python3
>>> import requests
>>> key ='<YOUR KEY HERE>"
>>> api_url = 'https://api.weather.com/v3/wx/forecast/dai-
ly/
5day?geocode=33.74,-84.39&format=json&units=e&language=en-
US&apiKey=' + key
>>> r = requests.get(api_url)
>>> forecast = r.json()
>>> for key in forecast:
... print(key)
(Note that when you’re interacting with Python in the terminal
this way, command-by-command, after entering a command that
requires an indented block of code such as for, use the TAB key
for each indented line that follows. You’ll see the three-dot ellipse
as evidence of the indentation. Hit return once again to end the
indented block.)
These commands will return
calendarDayTemperatureMax
calendarDayTemperatureMin
dayOfWeek
expirationTimeUtc
moonPhase
moonPhaseCode
moonPhaseDay
moonriseTimeLocal
moonriseTimeUtc
moonsetTimeLocal
moonsetTimeUtc
narrative
qpf
qpfSnow
Python and the Internet 173
GSW_RASPI_4ED_FIN.indd 173GSW_RASPI_4ED_FIN.indd 173 10/28/21 10:54 AM10/28/21 10:54 AM
sunriseTimeLocal
sunriseTimeUtc
sunsetTimeLocal
sunsetTimeUtc
temperatureMax
temperatureMin
validTimeLocal
validTimeUtcdaypart
so you can see exactly what keys are available to look at. Note that
‘daypart’ is a one-item list that contains a dictionary, so you can
dig a little deeper with
>>> for key in forecast ['daypart'][0]:
... print(key)
This will return
cloudCover
dayOrNight
daypartName
iconCode
iconCodeExtend
narrativeprecip
ChanceprecipType
qpf
qpfSnow
qualierCode
qualierPhrase
relativeHumidity
snowRange
temperature
temperatureHeatIndex
temperatureWindChill
thunderCategory
thunderIndex
uvDescription
uvIndex
windDirection
windDirectionCardinal
windPhrase
windSpeed
wxPhraseLong
wxPhraseShort
174 Getting Started with Raspberry Pi
GSW_RASPI_4ED_FIN.indd 174GSW_RASPI_4ED_FIN.indd 174 10/28/21 10:54 AM10/28/21 10:54 AM
As you can see, there’s a lot of information packed into this one
simple API call, and you can spend a lot of time with it to get the
information you want. But if you remember, we wanted a script that
would tell us if we need an umbrella. Because there’s a key inside
‘daypart’ called precipChance, we can just query that key’s value to
see the percent chance that it will rain that day. For a rain forecast
indicator, let’s say that any probability of precipitation value over
30% is a day that we want to have an umbrella handy.
1. Connect an LED to pin 25, as you did in Figure 6-5.
2. Create a new file called
umbrella-indicator.py
and use the
code in Example 10-2. Don’t forget to put in your own API key
and the location in the Weather Underground API URL.
3. Run the script as root with the command sudo python3um-
brella-indicator.py.
Example 10-2. Source code for umbrella-indicator.py
import requests
import time
from gpiozero import LED
key = '<YOUR API KEY HERE>'
latitude = '<YOUR LATITUDE>' Use quotes to make it a string
longitude = '<YOUR LONGITUDE>' # Again, use quotes
api_url = 'https://api.weather.com/v3/wx/forecast/daily/5day?
geocode=' + latitude +', ' + longitude +
'&format=json&units=e&language=en-US&apiKey=' + key
while True:
r = requests.get(api_url)
forecast = r.json()
pop_value = forecast['daypart'][0]['precipChance']
if pop_value is None:
pop_value = 0
if pop_value >= 30:
led.on()
else:
led.off()
time.sleep(180) # 3minutes
Python and the Internet 175
GSW_RASPI_4ED_FIN.indd 175GSW_RASPI_4ED_FIN.indd 175 10/28/21 10:54 AM10/28/21 10:54 AM
As before, change this to your API key.
Get today’s probability of precipitation and store it in popValue.
Convert popValue from a string into an integer so that we can
evaluate it as a number.
If the value is greater than 30, then turn the LED on.
Otherwise, turn the LED off.
Wait three minutes before checking again so that the script
stays within the API limit of 500 requests per day.
As you may have already discovered, there’s a small sticking point
in the API that we need to take into consideration in our script: if
there is no chance of precipitation on a particular day, the value
saved into the precipChance list is “None” This means that if we
check for the value of precipChance on that day, instead of getting
“0” back as a result, we’ll get None, which is literally “no value”. We
can’t compare “no value” to 30, so the script will fail if we try to run
it on a day with no precipitation in the forecast. To account for that
failure, if popValue is None, we set it to zero instead and go on about
our business.
Press Ctrl-C to quit the program when you’re done.
The Weather Underground API is one of a plethora of different APIs
that you can experiment with. Table 10-2 lists a few other sites and
services that have APIs.
Table 10-2.
Popular application programming interfaces
Site
API Reference URL
Facebook
developers.facebook.com
Flickr
www.flickr.com/services/api
Four-
square
developer.foursquare.com
Reddit
www.reddit.com/dev/api
Twilio
www.twilio.com
Twitter
dev.twitter.com
YouTube
developers.google.com/youtube
176 Getting Started with Raspberry Pi
GSW_RASPI_4ED_FIN.indd 176GSW_RASPI_4ED_FIN.indd 176 10/28/21 10:54 AM10/28/21 10:54 AM
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset