API Contract Testing with Postman

Shivendra Odean
Level Up Coding
Published in
4 min readJan 16, 2019

I’m going to show you a simple way of testing API contracts using Postman and Node.js. You can set this up very quickly.

I am building a mobile app for my current company. One of the challenges we face are the frequent changes to the API endpoints/contract. We also face communication challenges because we are collocated — developers working on this particular API reside in Barcelona, Spain whereas I am in New Zealand.

I needed a mechanism which provides early and consistent feedback on changes to those API contracts. Writing integration tests seemed too heavy, and I needed something that could be done much quicker.

My solution to the problem

Firstly we will be using a tool called Postman. Postman is a very useful tool that aids API development. It enables the creation of HTTP requests, saving and sharing collections of requests, writing tests against responses from these requests, and much more.

Secondly, we will write a Javascript file which will allow us to run these Postman requests and tests in an automated fashion.

I will try my best to describe each step. I apologize to the more experienced readers if it’s oversimplified, and to the lesser experienced technologists if I have not explained enough. You can find the code for this on Github here — https://github.com/shivendraodean/api-contract-testing

Let’s start! Please download the following tools -

1 — Create a basic API Project

Figure 1 — Project details

Copy and paste the below commands one line at a time into a terminal.

npm init will prompt for more information, fill in according to figure 1.

mkdir api-contract-testing
cd api-contract-testing
npm init
touch app.js
touch apiContractTest.js
npm install express newman

Copy and paste the following into app.js. This is a basic express.js server application. Line 11 is basically the root route which will return us some data.

const express = require('express')
const app = express()
const port = 3000
const testData = {
firstName: 'Homer',
lastName: 'Simpson'
}
app.get('/', (req, res) => res.send(testData))app.listen(port, () => console.log(`Server listening on port ${port}`))

Save the file and execute the following command. Then open a web browser and navigate to http://localhost:3000

This result is what we will now test with postman.

node app.js

2 — Create a Postman Collection

2.1 — Create a new get request

2.2 — Click on the Tests tab to add a test to the request. The schema refers to a global variable, which we will define in the next step. Paste the following.

pm.test("Homer's schema should be correct", function() {
var response = pm.response.json();

var result=tv4.validateResult(response, schema)
pm.expect(result.valid).to.be.true;
});

Next we define the schema. I generated the schema from this web app -https://jsonschema.net/#/

It basically allows you to paste in any JSON on the left side, and infers the JSON schema on the right which you can then copy and use.

Click on Pre-request Script and paste the following —

schema = {
"definitions": {},
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "http://example.com/root.json",
"type": "object",
"title": "The Root Schema",
"required": [
"firstName",
"lastName"
],
"properties": {
"firstName": {
"$id": "#/properties/firstName",
"type": "string",
"title": "The Firstname Schema",
"default": "",
"examples": [
"Homer"
],
"pattern": "^(.*)$"
},
"lastName": {
"$id": "#/properties/lastName",
"type": "string",
"title": "The Lastname Schema",
"default": "",
"examples": [
"Simpson"
],
"pattern": "^(.*)$"
}
}
}

Now if you press ‘Send’, the request will be sent and the test will be run.

2.3 — Save request to collection. Now that you have a collection, you can open the Test Runner and run tests for the collection.

2.4 — Export collection. Click on the ellipse next to the collection and select ‘export’. Specify the root of your JS as the download destination.

3 — Programmatically run tests with Javascript

Copy the following script into apiContractTest.js.

const newman = require('newman')newman.run({
collection: require('./homer-simpson-api.postman_collection.json'),
reporters: 'cli',
})

Copy the following into the scripts section of your package.json file.

"contractTests": "node ./apiContractTest.js",

Now execute this, ensuring the API server is running—

npm run contractTests

There you have it. I hope you find this useful.

You can find the code for this on Github here— https://github.com/shivendraodean/api-contract-testing

Please like and share this if you found it helpful.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Responses (2)

What are your thoughts?