Writing tests for RESTful APIs in Python using requests – part 4: mocking responses

In this short series of blog posts, I want to explore the Python requests library and how it can be used for writing tests for RESTful APIs. This is the fourth blog post in the series, in which we will cover working mocking responses for unit testing purposes. Previous blog posts in this series talked about getting started with requests and pytest, about creating data driven tests and about working with XML-based APIs.

One thing that has been keeping me busy in the last couple of months is improving my software development skills. I’m currently working on a Python development project, and one of the tasks of a developer is writing good unit tests. When I was writing these tests, I ran into a challenge when I wanted to test a method that involves communicating with a REST API using the requests library.

Obviously, I don’t want to have to invoke the API itself in my unit tests, so I was looking for a way to mock out that dependency instead. One thing I considered was writing mocks for the API myself, until I stumbled upon the responses library (PyPI, GitHub). According to their homepage, this is ‘A utility library for mocking out the requests Python library’. Exactly what I was looking for.

So, what can you do with the responses library, and how can you use to your advantage when you’re writing unit tests? Let’s look at a couple of examples that involve creating mock responses for the Zippopotam.us API.

Creating a mock response
Let’s say that in our unit test, we want to test that our code handles an HTTP 404 returned by a REST API dependency as expected. This implies we need a way to ‘override’ the actual API response with a response that contains an HTTP 404 status code, and (maybe) a response body with an error message.

To use the responses library to create such a mock response, you’ll first have to add the @responses.activate decorator to your test method. In the test method body, you can then add a new mock response as follows:

@responses.activate
def test_simulate_data_cannot_be_found():
    responses.add(
        responses.GET,
        'http://api.zippopotam.us/us/90210',
        json={"error": "No data exists for US zip code 90210"},
        status=404
    )

When you use the requests library to perform an HTTP GET to http://api.zippopotam.us/us/90210, instead of the response from the live API (which will return an HTTP 200), you’ll receive the mock response, instead, which we can confirm like this:

response = requests.get('http://api.zippopotam.us/us/90210')
assert response.status_code == 404
response_body = response.json()
assert response_body['error'] == 'No data exists for US zip code 90210'

You can add any number of mock responses in this way.

Unmapped responses
If, during testing, you accidentally hit an endpoint that does not have an associated mock response, you’ll get a ConnectionError:

@responses.activate
def test_unmatched_endpoint_raises_connectionerror():
    with pytest.raises(ConnectionError):
        requests.get('http://api.zippopotam.us/us/12345')

Simulating an exception being thrown
If you want to test how your code handles an exception being thrown when you perform an API call using requests, you can do that using responses, too:

@responses.activate
def test_responses_can_raise_error_on_demand():
    responses.add(
        responses.GET,
        'http://api.zippopotam.us/us/99999',
        body=RuntimeError('A runtime error occurred')
    )

You can confirm that this works as expected by asserting on the behaviour in a test:

with pytest.raises(RuntimeError) as re:
    requests.get('http://api.zippopotam.us/us/99999')
assert str(re.value) == 'A runtime error occurred'

Creating dynamic responses
If you want to generate more complex and/or dynamic responses, you can do that by creating a callback and using that in your mock. This callback should return a tuple containing the response status code (an integer), the headers (a dictionary) and the response (in a string format).

In this example, I want to parse the request URL, extract the path parameters from it and then use those values in a message I return in the response body:

@responses.activate
def test_using_a_callback_for_dynamic_responses():

    def request_callback(request):
        request_url = request.url
        resp_body = {'value': generate_response_from(request_url)}
        return 200, {}, json.dumps(resp_body)

    responses.add_callback(
        responses.GET, 'http://api.zippopotam.us/us/55555',
        callback=request_callback,
        content_type='application/json',
    )

def generate_response_from(url):
    parsed_url = urlparse(url).path
    split_url = parsed_url.split('/')
    return f'You requested data for {split_url[1].upper()} zip code {split_url[2]}'

Again, writing a test confirms that this works as expected:

response = requests.get('http://api.zippopotam.us/us/55555')
assert response.json() == {'value': 'You requested data for US zip code 55555'}

Plus, responses retains all calls made to the callback and the responses it returned, which is very useful when you want to verify that your code made the correct (number of) calls:

assert len(responses.calls) == 1
assert responses.calls[0].request.url == 'http://api.zippopotam.us/us/55555'
assert responses.calls[0].response.text == '{"value": "You requested data for US zip code 55555"}'

Using the examples for yourself
The code examples I have used in this blog post can be found on my GitHub page. If you download the project and (given you have installed Python properly) run

pip install -r requirements.txt

from the root of the python-requests project to install the required libraries, you should be able to run the tests for yourself. See you next time!

New open source workshop: writing tests for REST APIs in Python with requests

Just a quick update to let you all know that I’ve just released the first version of a brand new open source workshop.

If you’re looking to learn how to write tests for RESTful APIs in Python using the requests library, head on over to my GitHub page to find a free and open source workshop on this very topic.

So far, it contains five series of examples, exercises and the corresponding answers for you to try out. As with all the other open source workshops, you’re absolutely free to use it in any way you want. Share it, teach it to others, discuss it with coworkers, whatever you like.

The only thing I’m asking you is to share your experiences with me. Is there anything missing? How did you use this workshop and what did you think?

Have fun and happy learning.

Writing tests for RESTful APIs in Python using requests – part 3: working with XML

Recently, I’ve delivered my first ever three day ‘Python for testers’ training course. One of the topics that was covered in this course is writing tests for RESTful APIs using the Python requests library and the pytest unit testing framework.

In this short series of blog posts, I want to explore the Python requests library and how it can be used for writing tests for RESTful APIs. This is the third blog post in the series, in which we will cover working with XML request and response bodies. Previous blog posts in this series talked about getting started with requests and pytest, and about creating data driven tests.

REST APIs and XML
While most REST APIs I encounter nowadays work with JSON as the preferred data format for request and response body bodies, from time to time you’ll encounter APIs that work with XML. And since XML is a little more cumbersome to work with XML in code compared to JSON (not just in Python, but in general), I thought it would be a good idea to show you some examples of how to create XML request bodies and how to parse and assert on XML response bodies when you’re working with the requests library.

For the examples in this blog post, I’ll be using an operation from the ParaBank REST API that can be used to submit bill payments. It’s available at

http://parabank.parasoft.com/parabank/services/bank/billpay

and takes, next to two query parameters specifying the source accountId and the bill amount, an XML request body containing specifics about the person to whom the payment is sent, i.e., the payee. Not surprisingly, this request body is sent to the API provider using an HTTP POST.

Creating XML request bodies using strings
I’d like to show you two distinct approaches to creating XML request bodies. The first one is the most straightforward one, but also the least flexible: creating a method that returns a string object containing the XML body:

def fixed_xml_body_as_string():
    return """
    <payee>
        <name>John Smith</name>
        <address>
            <street>My street</street>
            <city>My city</city>
            <state>My state</state>
            <zipCode>90210</zipCode>
        </address>
        <phoneNumber>0123456789</phoneNumber>
        <accountNumber>12345</accountNumber>
    </payee>
    """

Note the use of the triple double quotes to allow you to declare a multi-line string. Of course, instead of hard-coding our XML request body in our code, we could also read it from an XML (or text) file stored somewhere on our file system. The result is the same.

If we want to pass this XML request body to our API, we can do that like this:

def test_send_xml_body_from_string_check_status_code_and_content_type():
    response = requests.post(
        "http://parabank.parasoft.com/parabank/services/bank/billpay?accountId=12345&amount=500",
        headers={"Content-Type": "application/xml"},
        data=fixed_xml_body_as_string()
    )
    assert response.status_code == 200
    assert response.headers["Content-Type"] == "application/xml"

Note that we explicitly set the Content-Type header of the request to application/xml to make sure the provider understands that the request body should be interpreted as XML. Sending the XML request body is done by assigning the return value of our method returning the XML as a string to the data parameter of the requests post() method.

To check that our request has been received and processed successfully, we assert that the response status code equals 200 and that the response Content-Type header has a value of application/xml. We’ll take a closer look at the actual XML response body later on in this post.

Creating XML request bodies using ElementTree
The other approach to working with XML request bodies is to programmatically build them. Python contains a powerful library to do this, called ElementTree. We can import this into our module using

import xml.etree.ElementTree as et

Since an XML document is essentially a tree with a root node with child nodes attached to it, we start creating our XML request body by defining the payee root node:

payee = et.Element('payee')

We can then define an element name that is a child element of payee:

name = et.SubElement(payee, 'name')

We also need to assign an element value to the name element:

name.text = 'John Smith'

It’s not required for this example, but if you would have to add an attribute, say, type, with value fullName to the name element, you could do so like this:

name.set('type', 'fullName')

Creating the entire XML request body for our API call is a matter of repeating the above statements in the right order, with the right values:

def create_xml_body_using_elementtree():
    payee = et.Element('payee')
    name = et.SubElement(payee, 'name')
    name.text = 'John Smith'
    address = et.SubElement(payee, 'address')
    street = et.SubElement(address, 'street')
    street.text = 'My street'
    city = et.SubElement(address, 'city')
    city.text = 'My city'
    state = et.SubElement(address, 'state')
    state.text = 'My state'
    zip_code = et.SubElement(address, 'zipCode')
    zip_code.text = '90210'
    phone_number = et.SubElement(payee, 'phoneNumber')
    phone_number.text = '0123456789'
    account_number = et.SubElement(payee, 'accountNumber')
    account_number.text = '12345'
    return et.tostring(payee)

Note that we need to convert the element tree into a string before we can use it with the requests library. We can do this using the tostring() method.

While the approach using ElementTree might look a little more cumbersome than simply specifying our XML as a string, it gives us the option of creating more complex and flexible XML documents by creating loops to repeat XML blocks, working with data sources that are transformed into XML, and so on. I myself don’t really prefer one approach over the other, but I think it’s good to be aware of both and choose the one that best fits your requirements.

If we want to use the XML created using ElementTree above as a request body, we can do that in exactly the same way as when we used a string containing the XML:

def test_send_xml_body_from_elementtree_check_status_code_and_content_type():
    response = requests.post(
        "http://parabank.parasoft.com/parabank/services/bank/billpay?accountId=12345&amount=500",
        headers={"Content-Type": "application/xml"},
        data=create_xml_body_using_elementtree()
    )
    assert response.status_code == 200
    assert response.headers["Content-Type"] == "application/xml"

Parsing and working with XML response bodies
Now that we have covered creating XML request bodies, let’s see what we can do with XML responses. By far the most powerful way to create specific assertions is to convert the XML response body into an ElementTree and then asserting on its properties.

As an example, we’re going to perform an HTTP GET call to

http://parabank.parasoft.com/parabank/services/bank/accounts/12345

which returns details of the account with ID 12345. If we want to assert, for example, that the root node of the XML response is named account, and that it has neither any attributes nor a text value, we can do this as follows:

def test_check_root_of_xml_response():
    response = requests.get("http://parabank.parasoft.com/parabank/services/bank/accounts/12345")
    response_body_as_xml = et.fromstring(response.content)
    xml_tree = et.ElementTree(response_body_as_xml)
    root = xml_tree.getroot()
    assert root.tag == "account"
    assert len(root.attrib) == 0
    assert root.text is None

Note that we first have to convert the XML response body to an object of type Element using the fromstring() method, then create an ElementTree out of that using the ElementTree() constructor, which takes an Element as its argument.

If we’re interested in the text value of a specific subelement of the XML response, for example customerId which contains the ID of the customer to whom this account belongs, we can do that by finding it in the ElementTree using the find() method, then write an assertion on the text property of the found element:

def test_check_specific_element_of_xml_response():
    response = requests.get("http://parabank.parasoft.com/parabank/services/bank/accounts/12345")
    response_body_as_xml = et.fromstring(response.content)
    xml_tree = et.ElementTree(response_body_as_xml)
    first_name = xml_tree.find("customerId")
    assert first_name.text == "12212"

It’s good to know that the find() method returns the first occurrence of a specific element. If we want to return all elements that match a specific name, we need to use findall() instead:

def test_use_xpath_for_more_sophisticated_checks():
    response = requests.get("http://parabank.parasoft.com/parabank/services/bank/customers/12212/accounts")
    response_body_as_xml = et.fromstring(response.content)
    xml_tree = et.ElementTree(response_body_as_xml)
    savings_accounts = xml_tree.findall(".//account/type[.='SAVINGS']")
    assert len(savings_accounts) > 1

As you can see, next to passing element names directly, we can also use XPath expressions to perform more sophisticated selections. The expression

 .//account/type[.='SAVINGS']

in the example above selects all occurrences of the type element (a child element of account) that have SAVINGS as their element value.

Using the examples for yourself
The code examples I have used in this blog post can be found on my GitHub page. If you download the project and (given you have installed Python properly) run

 pip install -r requirements.txt

from the root of the python-requests project to install the required libraries, you should be able to run the tests for yourself. See you next time!