Putting it all together: The Library of Congress API
To hone your API skills, you're now going to check out another API, the Library of Congress API. You're going to search the Library of Congress for all their content concerning New York City. You'll then print out the material relevant to the first entry.
This exercise is part of the course
Importing Data in Python
Exercise instructions
- Import the
requestspackage (you're probably pretty good at this by now!). - Apply the
json()method to the response objectrand store the resulting dictionary in the variablejson_data. -
json_data['items']is a list of items returned from your query: assign the first such item to the variablenyc_loc. - Hit
Submit Answerto print the key-value pairs of the dictionarynyc_locto the shell.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Import package
# Assign URL to variable: url
url = 'http://chroniclingamerica.loc.gov/search/titles/results/?terms=new%20york&format=json'
# Package the request, send the request and catch the response: r
r = requests.get(url)
# Decode the JSON data into a dictionary: json_data
# Select the first element in the list json_data['items']: nyc_loc
# Print each key-value pair in nyc_loc
for k in nyc_loc.keys():
print(k + ': ', nyc_loc[k])