API script examples

This guide outlines some examples with response validation, variable creation, and running console logs for debugging purposes.

📘

Postman JavaScript Object

Thanks to the mabl integration with Postman, you can use any Postman-supported JavaScript objects and functions to handle your custom logic and response validations.

Response validation

We recommend using our low-code assertion functionality to validate that the API returns the expected result. However, if you need to create a more complex assertion, you can create a custom assertion using JavaScript.

REST APIs with JSON payloads

To validate data in a response JSON body, you can use code like the one below:

pm.test("Person is Jane", () => {
  
  //assigning the response body to a constant.
  const responseJson = pm.response.json(); 
  
  //assert that the third person object in the response has name and age properties with a given value.
  pm.expect(responseJson.person[3].name).to.eql("Jane"); 
  pm.expect(responseJson.person[3].age).to.eql(23); 
});

To validate the length of an array, you can add the following snippet inside of the above pm.tests() function: pm.expect(responseJson.person).to.have.lengthOf(15);

In the previous example, if the person's name you want to assert against is stored in a variable such as personName you can replace the static string "Jane" with a variable value so that the code for that assertion looks like this: pm.expect(responseJson.person[3].name).to.eql(pm.variables.get("personName"));

SOAP APIs with XML payloads

You can use the following scripting approach to create assertions that validate data in an XML-based response body:

  • Convert the XML body to a JSON object using the built-in xml2json library.
  • Use JSON path notation or iterate over the object keys to find the target property you would like to assert on.

Example: Send a POST request to the following endpoint: https://www.w3schools.com/xml/tempconvert.asmx (converts temperature from Fahrenheit to Celsius degrees). Use one variable (e.g. tempF = 32) to pass the Fahrenheit input in the body of the request and use a second variable to validate the expected Celsius result (e.g. tempC = 0) in the response body.

Here's what you need to enter for the API test step:
Method: POST
URL: https://www.w3schools.com/xml/tempconvert.asmx
Headers:

  • Content-Type = text/xml
  • SOAPAction = https://www.w3schools.com/xml/FahrenheitToCelsius
  • Request body: see the following script.
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
     <FahrenheitToCelsius xmlns="https://www.w3schools.com/xml/">
       <Fahrenheit>{{tempF}}</Fahrenheit>
     </FahrenheitToCelsius>
    </soap:Body>
</soap:Envelope>

When you send that POST request, you should get a response body with the temperature degrees in Celsius (e.g. 32°F converts to 0°C).

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <FahrenheitToCelsiusResponse xmlns="https://www.w3schools.com/xml/">
      <FahrenheitToCelsiusResult>0</FahrenheitToCelsiusResult>
    </FahrenheitToCelsiusResponse>
  </soap:Body>
</soap:Envelope>

To assert that the <FahrenheitToCelsiusResult>0</FahrenheitToCelsiusResult> value equals the value of the tempC variable, you can write the following script in the Validation and variable assignment section of the API step.

pm.test("Validate conversion Fahrenheit To Celsius produces the expected result", () => {
    //convert XML response body to a JSON object using xml2Json library
    const responseJson = xml2Json(pm.response.text());

    //Use JSON path syntax to get to the target property 
    let result = responseJson["soap:Envelope"]["soap:Body"].FahrenheitToCelsiusResponse.FahrenheitToCelsiusResult;

    //Assert that result is the correct value
    pm.expect(result).to.eql(pm.variables.get("tempC"));
});

Variable creation

Creating variables based on JSON data

You can create variables based on an API response in (JSON) using code that looks like the following:

var jsonData = JSON.parse(responseBody);

//assign the third person's object id to a variable named userID
postman.setEnvironmentVariable("userID", jsonData.person[3].id);

Creating variables based on XML data

Creating a variable based on an API response body in XML format requires the same initial steps that it takes to validate data in an XML-based response body:

  • Convert the XML body to a JSON object using the built-in xml2json library.
  • Use JSON path notation or iterate over the object keys to find the target property value that you want to assign to a variable.

For example, using the same API endpoint described in the assertion section above that converts temperature from Fahrenheit to Celsius degrees, you can assign the resulting Celsius degrees to a variable called myTemperature with the following script.

//convert XML response body to a JSON object using xml2Json library
const responseJson = xml2Json(pm.response.text());

//Use JSON path syntax to get to the target property value to be assigned to a variable
let result = responseJson["soap:Envelope"]["soap:Body"].FahrenheitToCelsiusResponse.FahrenheitToCelsiusResult;

//Assign the result value to a given variable name
pm.environment.set("myTemperature", result);

The variable creation script is very similar to the assertion script in the prior section. The main difference is the target value is being assigned to a variable instead of being validated with an assertion.

In order to see the updated myTemperature variable value when you send the request, you can add myTemperature to the variables list in the left side pannel of the API test editor.

Console logs

API tests also support console logs, which can be useful for debugging. Console logging works with all API test scripts: pre-request scripts, test scripts, and flow-level scripts.

📘

Using log statements

The following log statements are supported:

  • console.log()
  • console.info()
  • console.warn()
  • console.error()

Viewing output

The output of your console log statements is visible in the API Test Editor, API Test Output page for cloud runs, as well as the output of local runs via the CLI.

In the API Test Editor, when you click the Send button, the console logs will be available as a tab in the Results panel:

11861186

For a cloud run, you can find console logs for each step of your API test on the Test Output page:

14041404

Console logs are also included in the output from API tests executed with the mabl CLI:

API test with console log

→ 
  ┌
  │ 'Reticulating splines before API request.'
  │ 'Reticulating complete:', { splineCount: 42, averageReticulation
  │ 9m: 0.98 }
  └
  GET https://localhost:8080/test/splines  OK, 1kB, 243ms]
  ┌
  │ 'Resetting splines after request.'
  └
  ✓  Status equals 200

┌─────────────────────────┬────────────────────┬───────────────────┐
│                         │           executed │            failed │
├─────────────────────────┼────────────────────┼───────────────────┤
│              iterations │                  1 │                 0 │
├─────────────────────────┼────────────────────┼───────────────────┤
│                requests │                  1 │                 0 │
├─────────────────────────┼────────────────────┼───────────────────┤
│            test-scripts │                  1 │                 0 │
├─────────────────────────┼────────────────────┼───────────────────┤
│      prerequest-scripts │                  1 │                 0 │
├─────────────────────────┼────────────────────┼───────────────────┤
│              assertions │                  1 │                 0 │
├─────────────────────────┴────────────────────┴───────────────────┤
│ total run duration: 307ms                                        │
├──────────────────────────────────────────────────────────────────┤
│ total data received: 102B (approx)                               │
├──────────────────────────────────────────────────────────────────┤
│ average response time: 243ms [min: 243ms, max: 243ms, s.d.: 0µs] │
└──────────────────────────────────────────────────────────────────┘
10:34:07 AM -  Test Passed

Learn more

Please, refer to the Postman documentation for complete scripting reference.


Did this page help you?