Requests Module

The reason we’ll use requests is that it’s very easy to use. For example it will read and use cookies
without having to do anything and is very easy to use SSL, set authentication
parameters, additional headers and parameters.
Also it’s very easy to handle the response data.

The disadvantage is that it’s not a built in library or
commonly available in most default Python installs. For that reason some people prefer to use
urllib2, so there are no dependencies.
But if you decide to go down that route you’ll need to build your
authentication header manually and read in and set cookies manually too.

However requests is easily installed using pip, yum or
apt-get. I recommend you use pip to
ensure you’re using a recent version.

To setup requests on Ubuntu 16.04 then all you should need to do is:

apt-get install python-pip

pip install requests

RIPE who is

To start off then we’ll use the RIPE whois REST API as its freely available on the Internet, so all you’ll require is access to the
internet, a copy of python and the requests module.

Example 1

The RIPE API is unauthenticated so to get started all we do
is the following from the interactive prompt:

import requests

r = requests.get('http://rest.db.ripe.net/ripe/mntner/RIPE-DBM-MNT')

Our response object is now stored as ‘r’, so we can examine
the response data with the following:

r.status_code

r.headers

r.text

You can also take a look at what other attributes are
available with the following

dir(r)

Example 2

You’ll notice that in the above example the response data
(ie r.text) was in XML format. In the
next example we’ll do the same query but ask the API to give use JSON data back
by using the ‘Accept’ header. Also, to
make full use of the requests module, we’re now going to create a session
object called ‘s’:

import requests, json

s = requests.session()

s.headers.update({'Accept':
'application/json'})

r = s.get('http://rest.db.ripe.net/ripe/mntner/RIPE-DBM-MNT')

You can now use some of the commands you learnt in Example 1 to look
at the response object. In particular
you’ll notice that the response data is now in JSON format.

r.text

The request module will also
convert the output into JSON and I can also pull out a single value from this easily.