Simple Python for Querying an API

Here is a short video and code sample for pulling a random cat fact from the Cat Facts API available here.

# First, we need to import a tool (called a "library") that helps us get data from the internet
# The 'requests' library makes it easy to fetch data from websites and APIs
import requests
# We also need the json library to help us display the data nicely
import json

# We use requests.get() to fetch data from a website
# 'https://catfact.ninja/fact' is the website address (URL) that gives us random cat facts
# This is like typing that address into your web browser
response = requests.get('https://catfact.ninja/fact')

# The website sends back data in a format called JSON (which looks like {key: value})
# .json() converts this data into something Python can easily work with (called a dictionary)
fact_data = response.json()

# First let's see what the raw JSON data looks like
# json.dumps() converts the data to a string, and indent=2 makes it look pretty
print('🐱 Here is the raw JSON data from the API:')
print(json.dumps(fact_data, indent=2))

# Now fact_data looks something like this: {'fact': 'Cats sleep 16 hours a day.', 'length': 26}
# We can get just the fact by using fact_data['fact']
# This is like looking up a word in a dictionary - we look up 'fact' to get the actual cat fact

# Print a blank line to separate the raw data from the fact
print('\n🐱 Here is your random cat fact:')
# Print the actual cat fact we got from the website
print(fact_data['fact'])