Find an API that is free and preferably has some python examples to work from. In this guide we’ll track this day in history as an example. We’ll use http://history.muffinlabs.com/date
Sign up for an account if needed (may be called “developer account”) and get any secret keys you need. Some APIs don’t require a secret key. The first examples below do not require a special key.
Use this code to see if your request is successful: history_api.py
(you can change the date on the end of the URL)
You want to see <Response [200]> in the shell window
Use this code to get any raw data: history_api_2.py
You will see a summary of the data, compressed in the shell. In this case, there’s a lot of data...too much for our purposes.
Use this tool to see how the JSON data is nested and organized:
https://jsonformatter.curiousconcept.com/
Paste your URL in and press “process”
Decide what specific data you want to retrieve. For example, let’s get the text of the very first event listed. We need to go down a couple of nested levels into the JSON data to get what we want.
This code will print only the text from
"Events" list item 0 history_api_3.py
This example will get the final item on the list, which will be the most recent occurrence and list the date history_api_4.py
If you want to check more than once, you can use a loop. Keep in mind that most APIs have a limit. If you call too often you will be temporarily limited, and will get error messages.
This example repeats every 20 seconds picking one of 20 random items: history_api_5.py
Challenges:
Print something that happened on Valentine's Day before 1800 and one thing that happened within the last 10 years.
Print something that happened on April 1st as well as where the source of the information came from.
Can you create a loop that prints the most recent event from 7 days in a row?