https://www.dataquest.io/blog/python-api-tutorial/
The json library has two main functions:
json.dumps()
— Takes in a Python object, and converts (dumps) it to a string.json.loads()
— Takes a JSON string, and converts (loads) it to a Python object.The dumps()
function is particularly useful as we can use it to print a formatted string which makes it easier to understand the JSON output, like in the diagram we saw above:
import json
def jprint(obj):
text = json.dumps(obj, sort_keys=True, indent=4)
print(text)
jprint(response.json())
Using an API with Query Parameters
We can do this by adding an optional keyword argument, params
, to our request. We can make a dictionary with these parameters, and then pass them into the requests.get
function. Here’s what our dictionary would look like, using coordinates for New York City:
params = {
'lat': 40.71,
'lon': -74
}
It’s almost always preferable to setup the parameters as a dictionary, because requests
takes care of some things that come up, like properly formatting the query parameters, and we don’t need to worry about inserting the values into the URL string.
response = requests.get('<https://somewebsite.com>', params= params)
Understanding the Pass Times
The JSON response matches what the documentation specified:
message
, request
, response
response
, contains a list of pass timesrisetime
(pass start time) and duration
keys.Let’s extract the pass times from our JSON object:
pass_times = response.json()['response']
jprint(pass_times)
[
{
"duration": 395,
"risetime": 1568082479
},
{
"duration": 640,
"risetime": 1568088118
},
{
"duration": 614,
"risetime": 1568093944
},
{
"duration": 555,
"risetime": 1568099831
},
{
"duration": 595,
"risetime": 1568105674
}
]