Fun with Cats – Python API Calls

One of the great things about Python as a programming language is that you can do fairly powerful things with just a few lines of code. In this article we are going to look at how to do a simple API call in Python to retrieve a random cat and display it on the screen.

API calls are everywhere on the internet. Although you will not need to know a huge amount about them for school-level Computer Science, it is important to have a basic knowledge of them. Besides they can be a lot of fun.

Retrieve a Cat

Here’s an example, which retrieves a random cat from an API called CATAAS (Cat as a service)

import urllib.request
import turtle

screen = turtle.Screen()

url = 'https://cataas.com/cat/gif'
filename = "random-cat.gif"
urllib.request.urlretrieve(url, filename)

screen.bgpic('random-cat.gif')

turtle.done()

Pretty neat eh?

Adding Sound

If you spend much time using Python, you will eventually come across the need to extend its power using packages. Leaning how to do this can take some effort, and can be more or less easy depending on your setup. If you have a recent version of Python (3.4 upwards), then you can use pip install playsound from a command prompt window. Otherwise, if you ae using something like WinPython you can install packages using a GUI. If this sounds like voodoo, maybe leave the next part of this activity for now.

The package we will use to add sound is playsound. Once you have installed it, download meow.mp3 into the same folder as your program, and modify you code to look like this:

import urllib.request
import turtle
import playsound

screen = turtle.Screen()

url = 'https://cataas.com/cat/gif'
filename = "random-cat.gif"
urllib.request.urlretrieve(url, filename)

screen.bgpic('random-cat.gif')

playsound.playsound('meow.mp3', True)

turtle.done()

Your cat should now meow for you.

In future articles, we will look at more API calls. Hopefully for now this has provided you with a fun introduction.

Sharing is caring!

1 Comment on “Fun with Cats – Python API Calls

Leave a Reply

Your email address will not be published. Required fields are marked *