9. Mini project: Cat Facts and Jokes
Now let's put everything from this chapter to work in a small but complete program. Two APIs, real network calls, timeouts, basic error handling, JSON parsing, and friendly output.
The full workflow, end to end:
- Make a request, with a timeout.
- Check for errors.
- Parse the JSON body.
- Display the results.
As you read the code, pay attention to how it's organised into functions. One function per API. This is the structure you'll use in every real-world project later in the book.
Save this at the project root as cat_facts_and_jokes.py:
"""
Cat Facts and Jokes
A simple program that fetches random data from two different APIs.
"""
import requests
def get_cat_fact():
"""Fetch a random cat fact from catfact.ninja."""
try:
url = "https://catfact.ninja/fact"
response = requests.get(url, timeout=5)
response.raise_for_status()
return response.json()["fact"]
except requests.exceptions.RequestException as e:
return f"Couldn't fetch cat fact: {e}"
def get_joke():
"""Fetch a random joke from official-joke-api."""
try:
url = "https://official-joke-api.appspot.com/random_joke"
response = requests.get(url, timeout=5)
response.raise_for_status()
data = response.json()
return f"{data['setup']} ... {data['punchline']}"
except requests.exceptions.RequestException as e:
return f"Couldn't fetch joke: {e}"
# Main program
print("=" * 50)
print("CAT FACTS & JOKES")
print("=" * 50)
print("\nHere's a cat fact for you:")
print(get_cat_fact())
print("\nAnd here's a joke:")
print(get_joke())
print("\n" + "=" * 50)
Run it from the project root:
$ python cat_facts_and_jokes.py
==================================================
CAT FACTS & JOKES
==================================================
Here's a cat fact for you:
Cats sleep for 70% of their lives, which means a 9-year-old cat
has been awake for only three years of its life.
And here's a joke:
Why don't scientists trust atoms? ... Because they make up everything!
==================================================
What you just built
This isn't a toy script; it's a small set of patterns you'll see in real production code. Six things deserve naming:
- Multi-API integration. Two different APIs from the same script, each with its own function so failure in one doesn't bring down the other.
- Timeout on every request. No hanging calls, no infinite waits.
- Basic error handling per call. Each function catches common network, timeout, and HTTP errors, returning a readable failure message instead of crashing on request failures.
- JSON parsing. Specific fields extracted from two different JSON response shapes.
- Clear documentation. Docstrings tell you what each function does, which becomes essential as your scripts grow.
- User-friendly output. Clean formatted messages, not raw JSON blobs.
None of these are advanced. They're foundational habits you can apply to every API project. Starting with these patterns now means you won't have to unlearn brittle, "demo-only" code later.
Your turn: extend this program
Practice is where this really sticks. Try these challenges to extend the program and test your understanding. Each builds on something you learned earlier in the chapter.
- Add user choice. Let users choose whether they want a cat fact or a joke using
input(). Only display the option they ask for. - Add a third API. Integrate
https://uselessfacts.jsph.pl/api/v2/facts/random?language=ento show random facts. Parse the JSON and extract thetextfield. - Create a loop. Wrap everything in a
while Trueloop so users can request multiple facts and jokes. Add a "quit" option to exit gracefully. - Add parameters. Modify
get_cat_fact()to accept amax_lengthargument. Use theparamspattern from Section 8 to request shorter facts:params={"max_length": 50}. - Save the results. Append each cat fact or joke to a text file so the program keeps a small history between runs.
Try each one before looking up an answer. If you're stuck for more than fifteen minutes, that's a sign to check the chapter resources or ask, but always make a serious attempt first. The struggle is where the learning happens.
Next: a quick recap of everything this chapter covered, plus a short quiz to lock it in.