Generating jokes in Python with the help of APIs.

In this tutorial, we are going to learn how to interact with application programming interfaces in Python. Retrieving information from application programming interfaces or APIs is a very useful skill that you can add to your skillset. Now, we are going to retrieve a random joke from the API provided by the following link : https://icanhazdadjoke.com/api.

Joke Generator using Python

Let us first go through our plan of action:

  • Get the URL of the API that we will be using.
  • get response and validate internet connection.
  • Take a keyword
  • Return all jokes.

Let us have a look at the complete code:

import requests
jokeitem = input("You want a joke on? ")
information = requests.get(f"https://icanhazdadjoke.com/search?term={jokeitem}", headers= {"Accept":"application/json"})
connection = information.ok
result = information.json()
l_no_of_jokes = result["results"]
no_of_jokes = len(l_no_of_jokes)
response=""
if no_of_jokes==0:
  while no_of_jokes==0:
    response = input("Try some other word(Type 'quit' to quit): ")
    if response=="quit":
      break
    else:	
        information = requests.get(f"https://icanhazdadjoke.com/search?term={response}", headers= {"Accept":"application/json"})
        result = information.json()
        l_no_of_jokes = result["results"]
        no_of_jokes = len(l_no_of_jokes)

if response!="quit":
  information = requests.get(f"https://icanhazdadjoke.com/search?term={response}", headers= {"Accept":"application/json"})
  l_no_of_jokes = result["results"]
  no_of_jokes = len(l_no_of_jokes)
  print(f"There are {no_of_jokes} joke/s available.\n")
  print(f"The {no_of_jokes} jokes are:\n")
  x=0
  for each_joke in l_no_of_jokes:
    print(l_no_of_jokes[x]['joke'])
    x+=1

Code Explanation

PART 1:

The module that will help us talk with APIs is the “requests” module in Python. Use the following code in Windows PowerShell or equivalent if you do not already have the requests module installed.

python -m pip install requests
  1. Import the requests module.(line 1 in code)
  2. Take a joke topic from the user.(line 2)
  3. Let us hold the information that we will retrieve in a variable called information. The way to connect to a URL and it’s API is shown in line 3 of code.
  4. To check whether the connection is a valid one or not we can use the connection.ok method provided by the requests module.
  5. We will get the result from the website in JSON(JavaScript Object Notation) format. So let us create a variable called result which will contain the JSON data .(line 5 in code.)
  6. If you want to look how the JSON data looks, just print the result variable.
  7. Line 5 in the code converts JSON code to Python executable format. Now, you can run Python operations on this dictionary.
  8. The ‘result’ key in the dictionary holds a list of all jokes returned.

PART 2:

  1. Get the number of jokes returned by using the length function for lists.
  2. This is done to ensure that we are not returning jokes for a keyword that doesn’t exist.
  3. Write a while loop to ensure that the keyword is changes until a keyword that exists is entered by the user.
  4. If jokes do exist for the word entered by the user, the use code in line 3 again to obtain the JSON data. Then use code in line 5 to convert into a Python readable dictionary object. The look for the key-value pair in the dictionary which holds the jokes.
  5. Now, you will notice that all the jokes are placed in the lists.
  6. Now use standard Python code to show the user the number of jokes available and then loop over the list using a for loop and display all the jokes in separate lines.
  7. You can repeat the process of showing jokes to the user until the user types the word ‘quit’ in the console if you wish to.
  8. Now that you know how to access jokes from this API, you could hold all the jokes that you obtain as elements in a list. Then you could import the random module and use the choice function to display a random joke to the user.

This is the JSON code returned from the API for a keyword ‘hipster’:

{
  "current_page": 1,
  "limit": 20,
  "next_page": 1,
  "previous_page": 1,
  "results": [
    {
      "id": "GlGBIY0wAAd",
      "joke": "How much does a hipster weigh? An instagram."
    },
    {
      "id": "xc21Lmbxcib",
      "joke": "How did the hipster burn the roof of his mouth? He ate the pizza before it was cool."
    }
  ],
  "search_term": "hipster",
  "status": 200,
  "total_jokes": 2,
  "total_pages": 1
}

Output for keyword ‘cat’:

joke generator in Python with API

Now, you can use the knowledge obtained to retrieve data from a variety of other APIs.

 

Leave a Reply