DEV Community

Cover image for Consuming an API in Python using requests
Tawanda Nyahuye
Tawanda Nyahuye

Posted on

Consuming an API in Python using requests

In this tutorial, we will learn how to consume an API in python using the requests library. We are going to use the joke API by 15katz.

Creating a project

It is advised to create each python project in a separate virtual environment(to isolate Python projects on our computer so that each project has its own dependencies). So let's start by creating a virtual environment.

python -m venv c:\path\to\your-project
Enter fullscreen mode Exit fullscreen mode

Inside your virtual environment create a python file. Name it jokes.py

Now start your virtual environment as follows

.\Scripts\activate
Enter fullscreen mode Exit fullscreen mode

Install requests

In order to use the requests library, we need to install it first inside our virtual environment

pip install requests
Enter fullscreen mode Exit fullscreen mode

The code

Import the requests module and json(we need to make use of the JavaScript Object Notation)

import requests
import json
Enter fullscreen mode Exit fullscreen mode

Lets add a function to get our joke as well as a main function

def get_joke():
    api_end_point = "https://official-joke-api.appspot.com/jokes/random"
    joke = requests.get(api_end_point)
    json_data = json.loads(joke.text)
    print(json_data)


if __name__ == "__main__":
    get_joke()

Enter fullscreen mode Exit fullscreen mode

To get our joke from the joke API we are passing the link which is our API endpoint as an argument to the get() method which sends a GET request to the specified URL. To manipulate the data we are deserializing it with loads(). The main function is where we are calling our get_joke function which is the starting point of our program.

Now let's test our script. To run the script use the command below(if you are using CLI)

python jokes.py
Enter fullscreen mode Exit fullscreen mode

We should get a random joke like the one below

{
   "id":241,
   "type":"general",
   "setup":"What do you get when you cross a bee and a sheep?",
   "punchline":"A bah-humbug."
}
Enter fullscreen mode Exit fullscreen mode

Now we have done a pretty good job but we don't want to work with the data as a JSON object which in this case is a python dictionary.
Let's extract the data and print it separately. our jason_data variable is a dictionary, in order to get the values we specify the key(id, type, setup, and punchline are the keys in this case) e.g dictionary_name["key"]

Edit your python script to look like the code below

import requests
import json

def get_joke():
    api_end_point = "https://official-joke-api.appspot.com/jokes/random"
    joke = requests.get(api_end_point)
    json_data = json.loads(joke.text)   
    joke_id = json_data["id"]
    joke_type = json_data["type"]
    joke_setup = json_data["setup"]
    joke_punchline = json_data["punchline"]
    print(joke_id)
    print(joke_type)
    print(joke_setup)
    print(joke_punchline)


if __name__ == "__main__":
    get_joke()

Enter fullscreen mode Exit fullscreen mode

Output: You will get a random output but it should look like these

210
general
What do you call a dad that has fallen through the ice?
A Popsicle.
Enter fullscreen mode Exit fullscreen mode

Now you can play around with the print statements and print whatever you like

Grabbing a joke by category

Let's create a new function. We will call it get_joke_by_category and we will pass the category as a parameter to our function and we will then call our function with a category of our choice as an argument in main.

def get_joke_by_category(category):
    api_end_point = "https://official-joke-api.appspot.com/jokes/"+category+"/random"
    joke = requests.get(api_end_point)
    json_data = json.loads(joke.text)
    print(json_data)


if __name__ == "__main__":
    get_joke_by_category("programming")
Enter fullscreen mode Exit fullscreen mode

If we run our script we will get the output below. This time it has returned a list with a dictionary inside.

[
   {
      "id":16,
      "type":"programming",
      "setup":"What's the object-oriented way to become wealthy?",
      "punchline":"Inheritance"
   }
]
Enter fullscreen mode Exit fullscreen mode

To get the values this time we need to specify the index position since there is only one dictionary the index position is 0. In the case of extracting multiple jokes like 10, you will have to loop through all the jokes. this time we are just adding the index position before the dictionary key.dictionary_name[index_position]["key"].

def get_joke_by_category(category):
    api_end_point = "https://official-joke-api.appspot.com/jokes/"+category+"/random"
    joke = requests.get(api_end_point)
    json_data = json.loads(joke.text)
    joke_setup = json_data[0]["setup"]
    joke_punchline = json_data[0]["punchline"]
    print(joke_setup)
    print(joke_punchline)


if __name__ == "__main__":
    get_joke_by_category("programming")
Enter fullscreen mode Exit fullscreen mode

Output: This time we have printed the joke setup and the joke punchline only(It's random again so different from our JSON result)

What's the best thing about a Boolean?
Even if you're wrong, you're only off by a bit.
Enter fullscreen mode Exit fullscreen mode

The full code

import requests
import json


def get_joke():
    api_end_point = "https://official-joke-api.appspot.com/jokes/random"
    joke = requests.get(api_end_point)
    json_data = json.loads(joke.text)   
    joke_id = json_data["id"]
    joke_type = json_data["type"]
    joke_setup = json_data["setup"]
    joke_punchline = json_data["punchline"]
    print(joke_id)
    print(joke_type)
    print(joke_setup)
    print(joke_punchline)


def get_joke_by_category(category):
    api_end_point = "https://official-joke-api.appspot.com/jokes/"+category+"/random"
    joke = requests.get(api_end_point)
    json_data = json.loads(joke.text)
    joke_setup = json_data[0]["setup"]
    joke_punchline = json_data[0]["punchline"]
    print(joke_setup)
    print(joke_punchline)


if __name__ == "__main__":
    get_joke_by_category("programming")
    #get_joke

Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)