Due 12/2 at 11:59pm
In this project, you will write a program that fetches random cat and dog facts from the internet using APIs.
Your program must meet the following specifications:
For example:
=== Fact Menu ===
1. Cat fact
2. Dog fact
3. Quit
Choice: 1
Fetching a cat fact...
Cats have five toes on their front paws, but only four toes on their back paws.
Choice: 2
Fetching a dog fact...
The average dog can run at speeds of up to 19mph.
Choice: 3
Goodbye!
This project uses the requests library, which is not part of Python’s standard library. Install it first:
pip install requests
You can send a request to a URL and get the response back as a dictionary using .json():
import requests
response = requests.get("https://catfact.ninja/fact")
data = response.json()
print(data["fact"])
Some APIs return more deeply nested data. The dog facts API returns a list of facts under "data", where each fact’s text is under "attributes":
import requests
response = requests.get("https://dogapi.dog/api/v2/facts")
data = response.json()
print(data["data"][0]["attributes"]["body"])
import requests
def get_cat_fact():
# TODO: send a request to https://catfact.ninja/fact and print the fact
pass
def get_dog_fact():
# TODO: send a request to https://dogapi.dog/api/v2/facts and print the fact
pass
while True:
print("\n=== Fact Menu ===")
print("1. Cat fact")
print("2. Dog fact")
print("3. Quit")
choice = input("\nChoice: ")
if choice == "1":
get_cat_fact()
elif choice == "2":
get_dog_fact()
elif choice == "3":
print("Goodbye!")
break
else:
print("Invalid choice. Try again.")
When you’re happy with your program, upload the .py file to ThinkWave.