REST API testing

Note
For this tutorial we will assume you are running Windows, but the steps are almost identical for macOS or Linux.
  1. If you haven’t done it already, please follow the instructions in the installation page, including the quick start section to install OpenTest and create the default configuration files.

    You should now have the OpenTest server and actor up and running from a directory structure similar to this:

    C:\opentest
    ├── server
    │   └── server.yaml
    ├── actor1
    │   └── actor.yaml
    └── test-repo
        └── ...
  2. Open the server’s web UI at http://localhost:3000.

  3. From the menu, select Session > Create Test Session. Select the test named GitHub API test and click Create session. Wait a few seconds for the test to complete.

Here’s the full source of the test we just ran:

test-repo-path/tests/api/GitHub API test.yaml
description: Get repo branches from the GitHub API
actors:
  - actor: ACTOR1
    segments:
      - segment: 1
        actions:
          - description: Perform the API call
            action: org.getopentest.actions.HttpRequest
            args:
              url: https://api.github.com/repos/facebook/react/branches
              verb: GET

          - description: Verify that the branches array exists and is not empty
            script: |
              var branches = $output.body;

              if (!branches || (branches.length == 0)) {
                  $fail("Response body invalid or contains no branch elements.");
              } else {
                  $log($format(
                    "The GitHub API returned {0} branches",
                    branches.length));
              }

The test above consists of two test actions:

  • The first action calls the /repos/facebook/react/branches API on api.github.com

  • The second test action performs a validation step making sure that:

    • some payload was returned;

    • the response payload is an array with at least one element (we’re not being very thorough, just checking that the length property of the array is greater than 0).

As opposed to most UI tests, in order to do proper validation of the API response payloads, you do need to have some familiarity with the basic syntax of the JavaScript language:

  • How to build an if statement.

  • How to compare two values using the == and != operators.

  • How to access an object property using the . operator.

  • How to perform a function call.

API tests are usually much easier to build than UI tests. The formula you’re going to apply over and over (with small variations) is:

  1. Call an API using the the HttpRequest keyword and save the statusCode and/or body output values into a variable.

  2. Add one or more script actions to validate the response payload and/or status code.

Here’s one more example of an API test. This one calls the JSONPlaceholder fake REST API:

description: Creates a new BLOG post and validates the response
actors:
  - actor: ACTOR1
    segments:
      - segment: 1
        actions:
          - description: Create a random post ID
            script: var postId = $random(1000, 99999);

          - description: Send a request to create a new blog post
            action: org.getopentest.actions.HttpRequest
            args:
              url: https://jsonplaceholder.typicode.com/posts
              headers:
                Content-Type: application/json
              verb: POST
              body: |
                $json(
                  {
                    id: postId,
                    title: "My fist post"
                  }
                )

          - description: Extract the response's status code and body
            script: |
              var statusCode = $output.statusCode;
              var postInfo = $output.body;

          - description: Validate the response status code
            script: |
              if (statusCode != 201) {
                $fail($format(
                  "We expected the status code to be {0} but it was {1}",
                  201,
                  statusCode));
              }

          - description: Validate the post ID
            script: |
              if (postInfo.id != postId) {
                $fail($format(
                  "We expected the post ID to be {0} but it was {1}",
                  postId,
                  postInfo.id));
              }

          - description: Validate the post title
            script: |
              if (postInfo.title != "My fist post") {
                $fail($format(
                  "We expected the post title to be '{0}' but it was '{1}'",
                  "My fist post",
                  postInfo.title));
              }

What next?

  • Let’s create and run your first API test. Create a new file named My API test.yaml in the tests directory of the test repo, then copy & paste in it the full contents of this last test we looked at. In the OpenTest web UI, create a new test session to run the test named My API test. When the test is finished, click on the test session link in the UI to examine the test results and look at the session log to understand the type of information available to you for troubleshooting. For extra points, modify one of the validation steps so that the test fails and run the session again. Then look at the log, to understand how the error information is displayed.

  • Read the documentation for the HttpRequest action to get a general idea of its arguments and capabilities.

  • Create a new issue on GitHub and ask a silly question. We don’t care, we answer all of them.