User API
API Testing Automated Testing Contract Testing

API Contract Testing with Postman

Introduction

In the previous blog, we delved into the concept of Contract Testing and examined the composition of an API contract. Today, we will practically apply this knowledge by executing a contract test using Postman, a widely popular tool in the API testing community. 

Contract testing ensures that services such as APIs adhere to their declared contract. In the realm of microservices, this type of testing is vital, as it verifies that changes in a service do not violate the contract and lead to detrimental ripple effects on other services. We will utilize Postman and AJV (Another JSON Schema Validator), a JSON schema validator, to validate these contracts.

To better understand the example, a basic knowledge of APIs and Postman is essential. Before proceeding, be sure to read our previous blog on contract testing to gain an understanding of the concept.

Importance of API Testing in Contract Testing

API Testing is crucial for ensuring that the APIs meet their specified requirements and perform reliably under various conditions. By incorporating API testing in our contract testing strategy, we can identify issues early, maintain the integrity of API interactions, and ensure seamless communication between microservices.

Table of Contents

API contract example

We will use the comments API for this blog. We will specifically use the GET comments/{randomId} endpoint, which provides us with a random comment. Although this API is not complex, it is a good starting point for creating a simple contract and implementing our test.

The response from this endpoint will appear as follows

json-schema

Creating a JSON Schema to use with Postman

Based on the API’s response, we can now generate a JSON Schema that describes the data structure. Here’s an example of what that schema might resemble:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "postId": {
      "type": "integer"
    },
    "id": {
      "type": "integer"
    },
    "name": {
      "type": "string"
    },
    "email": {
      "type": "string", "format": "email"
    },
    "body": {
      "type": "string"
    }
  },
  "required": ["postId", "id", "name", "email", "body"]
}

This schema validates that the response is an object with a “postId” integer, “id” integer, “name” String, “email” string and a “body” string, all of which are mandatory.

Setting up Postman

Create a new GET request in Postman. Set the request URL : https://jsonplaceholder.typicode.com/comments/

get-request

Adding AJV and Using the Schema for Validation

Here’s where AJV comes into play. AJV allows to validate JSON data against a JSON schema, which is perfect for contract testing. Postman’s test scripts can utilize the AJV library to validate the API response against our schema.

First, we need to create our schema in the Pre-request Script of our Postman collection. As shown below, we first generated a random number to include in the request and then created the schema.

test-scripts
pre-requisite-scripts
//Generate a random number between 1 to 100
function generareRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

//set the random number to a variable
const randomNumber = generareRandomNumber(1 , 100);
pm.variables.set("randomNumber", randomNumber);

// Define schema
pm.environment.set("postId_schema", {
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "postId": {
      "type": "integer"
    },
    "id": {
      "type": "integer"
    },
    "name": {
      "type": "string"
    },
    "email": {
      "type": "string", "format": "email"
    },
    "body": {
      "type": "string"
    }
  },
  "required": ["postId", "id", "name", "email", "body"]
});

Then add tests in Test section

add-test-in-test-section
// Initialize AJV
var Ajv = require('ajv');
ajv = new Ajv({logger: console});

// Set schema parameter (the variable we created in pre-request)
var schema = pm.environment.get("postId_schema");

// Set data parameter (the parsed json response body)
var data = pm.response.json();

// Check validation result
pm.test('Json response adheres to schema', function() {
    pm.expect(ajv.validate(schema, data)).to.be.true;
});

In this script, we retrieve the schema created in the pre-request script, initialize AJV, compile the schema using AJV, and validate the response body against the schema. If the validation fails, it logs the errors; if it passes, it logs a success message.

Running the Test

Once the test is set up, you can proceed to run it. Simply click “Send” to initiate the GET request. Once the request is finished, you can review the test results in the “Test Results” tab of the response section.

run-test

And that’s it! You’ve successfully set up and run a contract test using Postman and AJV. Contract testing can be a powerful tool in maintaining the integrity of your APIs, especially in microservice architectures. It ensures that services continue to interact seamlessly, even as individual services evolve. With tools like Postman and AJV, you can effectively keep your APIs’ contracts intact.

Conclusion

In conclusion, this blog highlighted the importance of contract testing and demonstrated how to perform it using Postman and AJV. Contract testing ensures that APIs comply with their defined contracts, thus maintaining smooth interactions between services. By utilizing Postman for API testing, we validated API responses against a specified JSON schema. This approach is particularly effective in microservice architectures, as it helps prevent integration issues and allows for smoother service evolution. Therefore, ensuring contract compliance is crucial. Stay tuned for more insights into API testing and other automation techniques in our upcoming posts.

Keep practising and exploring to master these powerful tools further with Jignect

Witness how our meticulous approach and cutting-edge solutions elevated quality and performance to new heights. Begin your journey into the world of software testing excellence. To know more refer to Tools & Technologies & QA Services.

If you would like to learn more about the awesome services we provide, be sure to reach out.

Happy Testing 🙂