Home > Articles > Sean's Raspberry Pi coding tutorials > Downloading random Dad jokes in Python

Downloading random Dad jokes in Python using the icanhazdadjoke.com API

Sean McManus shows how to download random jokes from the icanhazdadjoke website in Python, and have them spoken out loud using a text-to-speech module.

A computer-generated image of a man laughing with his son I love a good joke, and quite a few bad jokes, too. So I was excited when I saw that icanhazdadjoke.com offers an API for downloading what are often called Dad jokes.

It seems like a natural addition to my Raspberry Radio project, which reads out the news and weather and then announces your songs with a snippet of trivia before playing them. That project was documented in issues 121 and 122 of The MagPi magazine.

Below you can see a simple code example for downloading jokes. It contains the following elements:

  • An output function, which accepts a piece of text. It speaks the text out loud and also prints it to the screen. If you are combining this code with Raspberry Radio, this output routine is already in there.
  • Code to set up the headers and download a random joke from icanhazdadjoke.com. In the headers, you're asked to add your own agent name so that the people operating the site can understand who's using the API and how much. You could put an email address or other contact point.
  • Code to add a default joke. Using try/except it sets up a default joke if for some reason the API doesn't respond. To make the code more entertaining in even the darkest days of internet outage, you could add a number of jokes here and have one chosen at random as the fallback. For inspiration for jokes to add, you could try my random joke machine.
  • Code to initialise the voice. The way the text-to-speech works is explained in my article about Raspberry Radio for The MagPi magazine.
  • Code to work out what day of the week it is, so that the voice can start by saying "This will brighten your " with the correct day name inserted (just like it was there, assuming you have Javascript enabled). By the way, if you want an easy way to add smart time and date detection to your own webpages, see my Javascript Smart Marketing Toolkit.

Installing the dependencies

You'll need to install the required libraries. Open a terminal window and then enter the following instructions:

pip install pyttsx3
pip install requests

Python code to download random jokes from the internet

Here's the Python program that downloads a random joke, and then speaks it out loud. It's also displayed to the screen so if you don't have speakers you can still see what's going on. This program should work wherever Python runs and the libraries are available.

# Program to download a joke from icanhazdadjoke.com
# And say it out loud using text-to-speech
# by Sean McManus - www.sean.co.uk
    
import requests
import pyttsx3
from datetime import datetime
    
def output(text):
    print(text)
    voice.say(text)
    voice.runAndWait()
    
headers = {
    'User-Agent': 'YOUR_AGENT_NAME', # ADD YOUR OWN HERE
    'Accept': 'application/json'
}
    
try:
    data = requests.get("https://icanhazdadjoke.com/", headers=headers)
    joke = data.json().get('joke')
except:
    # standard joke here for if the random joke lookup fails
    joke = "What do clouds wear under their clothes? Thunderwear."
    
voice = pyttsx3.init()
voice.setProperty('rate', 170)
    
today = datetime.now()
day_of_week = today.strftime('%A')
output(f"This will brighten your {day_of_week}")
output(joke)

More Raspberry Pi projects

Find more Raspberry Pi projects and tutorials here.

Image created using Dall-E 2.

Credits

© Sean McManus. All rights reserved.

Visit www.sean.co.uk for free chapters from Sean's coding books (including Mission Python, Scratch Programming in Easy Steps and Coder Academy) and more!

Discover my latest books

Coding Compendium

Coding Compendium

A free 100-page ebook collecting my projects and tutorials for Raspberry Pi, micro:bit, Scratch and Python. Simply join my newsletter to download it.

Web Design in Easy Steps

Web Design IES

Web Design in Easy Steps, now in its 7th Edition, shows you how to make effective websites that work on any device.

100 Top Tips: Microsoft Excel

100 Top Tips: Microsoft Excel

Power up your Microsoft Excel skills with this powerful pocket-sized book of tips that will save you time and help you learn more from your spreadsheets.

Scratch Programming in Easy Steps

Scratch Programming IES

This book, now fully updated for Scratch 3, will take you from the basics of the Scratch language into the depths of its more advanced features. A great way to start programming.

Mission Python book

Mission Python

Code a space adventure game in this Python programming book published by No Starch Press.

Cool Scratch Projects in Easy Steps book

Cool Scratch Projects in Easy Steps

Discover how to make 3D games, create mazes, build a drum machine, make a game with cartoon animals and more!

Walking astronaut from Mission Python book Top | Search | Help | Privacy | Access Keys | Contact me
Home | Newsletter | Blog | Copywriting Services | Books | Free book chapters | Articles | Music | Photos | Games | Shop | About