We do API testing to ensure that the functionality and reliability of your application is correct. While testing the replies of the REST calls, you need to filter the JSON response data to extract the relevant information.

Introduction

I blogged in august already that we can do Rest Api Testing with Cypress. When working with APIs, it’s essential to extract specific data from the JSON responses to validate the behavior of your application. Let’s look how you can do that.

Making an API Request

Before I dive into filtering JSON data, I explain how to make an API request using Cypress. The cy.request() command allows to send HTTP requests and store the responses for further processing. Here’s an example of making an API request:

cy.request({
  method: 'GET',
  url: 'https://api.example.com/data',
}).as('apiResponse');

This code sends a GET request to the specified URL and aliases the response as apiResponse. We’ll use this alias to work with the response data. You can find more information in a previous blog post.

Filtering JSON Data

Once you have the API response, you can filter the JSON data to extract the information you need. Let’s consider a JSON response containing an array of objects, each with various properties:

[
  { "id": 1, "prio": 1 },
  { "id": 2, "prio": 2 },
  { "id": 3, "prio": 1 },
  // ...
]

To filter objects based on the prio property equal to 3, you can use the filter method. Here’s how you can do it:

cy.get('@apiResponse').then((response) => {
  // Use the filter method to get all objects with prio equal to 1
  const objs = response.body.filter((item) => item.prio === 3);
  // Now you can work with the filtered objects
  cy.log('Objects with prio 1:', objs);
});

Handling Nested Data

JSON responses can have complex structures with nested data. Let’s say your JSON response includes objects with a nested client object, and you want to filter based on the name property within the client object:

[
  {
    "id": 1,
    "client": {
      "name": "Name1"
    }
  },
  {
    "id": 2,
    "client": {
      "name": "Name1"
    }
  },
  {
    "id": 3,
    "client": {
      "name": "Name2"
    }
  },
  // ...
]

To filter objects based on the name property within the client object, you can adapt the filtering code like this:

cy.get('@apiResponse').then((response) => {
  // Use the filter method to get all objects with client name equal to "Name1"
  const objs = response.body.filter((item) => item.client && item.client.name === 'Name1');
  // Now you can work with the filtered objects
  cy.log('Objects with client name "Name1":', objs);
});

This code will filter and log all objects with a client object containing the name property equal to “Name1”.

Conclusion

By making API requests and using the filter method, you can easily extract and work with the relevant data in your JSON responses.

Happy automation with Cypress!

Resources

Photo by Tyler Nix