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