Skip to Main Content






Getting Started With APIs

Parsing JSON Responses

In this activity, you are asked to use The Cat API to get and print a randomly generated Cat Fact. This activity will utilize everything we have covered thus far, and will help you gain some hands-on experience on making GET requests with APIs, as well as allow you to practice parsing JSON responses.

On this page you will find:

  • An excerpt from The Cat API documentation to help familiarize yourself with the way the API works,
  • A "Fill In The Blanks Code" in which it is your job to fill in the the lines with three asterisks (***),
  • A very nice looking emotional support cat,
  • An an example solution to the code.

Good luck! 

Excerpt from Cat Fact API Documentation:

The Cat Fact API documentation provides information on how to use the API to get facts about cats. Here is
an overview of what the documentation typically includes:

1. Base URL: The base URL for the API, which is "https://catfact.ninja/facts".

2. Endpoints:
   - Facts: provides a list of ten facts about cats.
     GET /facts
     **Stores cat facts under the 'data' key in the JSON response.

Fill In The Blanks Code:

# Import the required libraries (Hint: there's two)
***
***

# Define the API endpoint for a random cat fact
url = "https://catfact.ninja/facts"

# Make a GET request to the API
***

# Parse the JSON response
***

# Extract the cat fact
***

# Print the cat fact
for fact in ***:
    print(***)

Sample Filled In Code:

# Import the required libraries (Hint: There's two)
import requests
import json

# Define the API endpoint for a list of cat facts
url = "https://catfact.ninja/facts"

# Make a GET request to the API
response = requests.get(url)

# Parse the JSON response
data = response.json()

# Extract the list of cat facts
cat_facts = data['data']

# Print each cat fact
for fact in cat_facts:
    print(f"Cat Fact: {fact['fact']}")