Making a GET Request from an API with Python

0
82

When it comes to using APIs that are available from vendors, there comes the need to build and format the initial request and then you will receive the data. The received data is usually in a format like JSON or XML for example. That data can then be modified or formatted to fit your needs. The first step in the process though is the actual GET request.

There may actually be other steps like authentication \ generating a token to begin using the API you are working with. This is a very basic example.

Building your GET Script

The Python module that will be used in this example and others to come is httplib2. This module allows for basic GET and POST requests from an http(s) url. In this case, I have a basic API that is free for testing (http://dummy.restapiexample.com/).

To begin my new script, we’ll begin as usual and then load the python module httplib2:

#!/usr/bin/env python
import httplib2

From here, we need to get the URL that we will request data from. In my case, from the URL I mentioned with the free test API, I want to get a list of test employees names. In this case, that URL to use is “http://dummy.restapiexample.com/api/v1/employees”. The next batch of code to actually make the request, looks like this:

api = httplib2.Http()
content = api.request("http://dummy.restapiexample.com/api/v1/employees", "GET")
print content

The API will return a long list of “employee” data. The print statement will display all of this data, which looks like a mess:

Your next step at this point is to take the data in JSON format and then filter the data in a way where you can display it or use it in a way that is more meaningful. Another topic for another time…

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.