API Testing: A Developer’s Tutorial and Complete Guide

I feel for you, front-end developers. Your toolchain is constantly changing. Is Angular still all the rage? Or is it…

Testim
By Testim,

I feel for you, front-end developers. Your toolchain is constantly changing. Is Angular still all the rage? Or is it Vue.js now? JavaScript or TypeScript? Not only that, but you have to create a beautiful and seamless user experience while ensuring the reliability of your app. Your apps also have to talk to remote web services, most of which you might not have any control over. And I’m sure you’ve felt some frustration while integrating with APIs that lack documentation.

However, have you thought about testing the APIs you integrate with? You might be asking yourself why you’d ever consider testing an app you have no responsibility for. In this post, I’ll show you how to write API tests and how it can help your life. Before we continue, let’s make sure we share the same definition of API testing.

API Tests

So what are API tests? API testing validates the functionality, behavior, and performance of web services. An API test sends an HTTP request to the service layer and then validates the response. For example, a company may have a web service that’s responsible for managing its product inventory. This web service has an endpoint for creating new products. A developer may want to test that when a request is made to the “create new product” endpoint without a valid product ID, the API returns a bad request response.

API Testing for Back-End Developers

Why do back-end developers test APIs? If you’re familiar with the test automation pyramid, you’ll know unit tests by themselves don’t cut it. A good test suite also includes integration and end-to-end tests, which is where API tests fall. API tests are as close to an end-to-end test as owners of back-end services can get. They also need a high level of integration because they should be executed from outside of the application. This means that the web service should be up and running with all of its dependencies, such as a database, before the tests begin.

Furthermore, back-end development teams should consider periodically running their API tests suite against their deployed apps in multiple environments such as development, stage, and even production. This is known as a smoke test. It can give development teams insights into the health of their applications before users experience an outage.

API Testing for Front-End Developers

Why should you as a front-end developer care about API tests? I promise you that API tests don’t just benefit back-end teams. Your apps probably have to integrate with external services whether it be to authenticate a user or fetch some data to display. Writing API tests from the moment you begin integrating with a web service is a great way to understand what endpoints are available to you and what their responses look like. I’m sure you’ve stumbled across a few APIs with inaccurate or out-of-date Swagger docs. Writing API tests early will help you catch these inaccuracies before you start to write your production code. This could save you a lot of headache down the road.

Much like how back-end developers can use API tests as smoke tests, you can use them as contract tests. Contract tests are a great way for your team to be notified when an external service’s response contract changes without your knowing. This may lead your team to update your application and may prompt a conversation with the back-end team as to why they didn’t inform you of a breaking change. Regardless, you can glean useful insights into your external service providers.

Now that you know what API testing is and some of its benefits, let’s dive into an example.

API Testing: An Example

Before we can write any API tests, you’re going to need an actual API. I’ll show you how to quickly and easily create a REST API using JavaScript and the Express web framework. You’ll need to make sure you have Node along with npm and npx. (The installation of Node should include npm and npx.) Express combined with Node can be used to develop powerful web apps with just a few lines of code.

The Express application generator will help you create a web app with one simple command. Execute the command npx express-generator api-example –no-view from a command prompt. If you don’t already have the express-generator package installed, npx will automatically download it for you. The –no-view option will create your app without a template engine since we only need a few endpoints to write our tests. Next, be sure to install the app dependencies using npm install.

You should now have a project that looks something like this.

This is a fully functioning web API! Didn’t I tell you that would be easy? Take a minute to digest the code. The app.js module contains most of the code to configure our web app, and the files located in the routes folder contain the endpoints of the API.

You can start the web app on your development machine by running npm start. Now you have an API you can test!

API Testing Tools

There’s an ever-growing number of tools available for testing APIs. Many of these tools allow developers to write tests using their favorite programming language or through graphical interfaces. Development teams should choose an approach they’re most comfortable with. Let’s look at a tool that uses JavaScript for writing tests.

SuperTest

A very popular API testing library is SuperTest. With SuperTest, you write your test suite in plain JavaScript and use your favorite test runner such as Jasmine, Jest, or Mocha. It uses the SuperAgent HTTP request library under the hood, which you might already be familiar with since it can make HTTP requests from a browser-based app. SuperTest has rich assertions built in with an easy-to-read syntax.

Let’s write a test for the GET /users/ endpoint in our API. Note, I’m using Jasmine as a test runner and for assertions.

const request = require('supertest');

describe('GET /users', function () {
  it('responds successfully with text ', function (done) {
    request('localhost:3000')
      .get('/users')
      .expect('Content-Type', /text/)
      .expect(200)
      .then(response => {
        expect(response.text).toBe('respond with a resource');
        done();
      });
  });
});

Let’s break down this code. SuperTest has a fluent interface that makes for great readability. And readable code should make you happy. First, the request function takes a parameter for the host that the API is located at. In your case, it’s localhost on port 3000, but it could easily be a remote URL. Next, the request is sent to the /users/ endpoint of the API. The test then expects that the response has a 200 OK status code and a Content-Type containing text. Finally, the body of the response is validated. The /users/ endpoint responds with text, but other data formats can be used, such as JSON.

This example only touches the surface of SuperTest’s capabilities, so I encourage you to check out their documentation further. Now that you’ve seen an example of an API test that follows a code-first approach, I’ll point you in the direction of some additional tools.

Additional Tools

SuperTest is a great utility if you prefer writing tests in JavaScript. However, if you’re looking for a way to write API tests using a GUI, take a look at Testim. Testim allows you to create API tests with an easy-to-use graphical interface that can be automated. You can even run additional JavaScript code after an API call to validate the response or use the returned data for later tests. Furthermore, Testim has integrations with tools that you already use such as Jenkins, Slack, and GitHub.

Conclusion

In this post, I introduced you to the concept of API testing. I also explained why back-end developers use API testing and how it can benefit front-end developers. I even showed you how to write an API test using SuperTest and recommended some alternative tools such as Testim. What’s the best approach? That’s for you to decide. I’d recommend experimenting with a few of the tools available to get a sense of what might work best for you and your team.

Want to learn more about automated testing solutions? Check out this guide from Testim.

This post was written by JT Wheeler. JT got his start working as an engineer in the manufacturing industry. From there, he moved on to become a developer at a software consulting firm. He’s written software that spans a number of industries ranging from industrial automation to inventory control to financial systems, and he’s passionate about learning and teaching new technologies and software practices.