API testing with python requests

API testing with python

Testing API’s in python is not difficult. We only need a library that can call a web service to test a REST API. I use the requests library to call REST API’s. The website of requests mentions the following:

Requests is an elegant and simple HTTP library for Python, built for human beings.

documentation of requests

That looks nice, no? On there website they give an example that can fetch a user from the github api. The API calls need some authentication with user and password.

import request
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))

That did not work in our situation. We have an authentication service that first gives us a bearer token. That token is send afterwards in the request header when calling al our other services. This means we need to fetch our token with our user and password before we do a call to another service.

import requests
url = "https://the.authentication.service.url/"
payload = dict(login="myname", password="mypassword", type="plain")
login = requests.post(url, data=payload)
token = login.json()['token']

The token we need for the other services is located in a json reply with a key “token”. Note that this is our implementation. Yours can be different.

Now it is time to call the other services. It took me a while to figure out how it works, but it is very simple. Lets give a code example:

service_url = "https://the.user.service.url"
headers = dict(authorization="bearer %s" % token)
reply = requests.get(service_url, headers=headers)
if reply.status_code == 200:
    print("The reply is: %s" % reply.json())

All our services send json back as a reply. This is afterwards very easy to parse to a python dict.

We test every web service with this simple piece of code. It is as simple as that.