If your API testing goals include requirements that cannot be accomplished through mabl’s low-code functionality, you can write custom scripts. In mabl, custom scripts are composed of one or more API snippets, which you can create and reuse across other API tests.
Custom scripts are helpful for handling more complex API testing and troubleshooting scenarios, including:
- Complex data extraction - extracting data from a response in a specific way that requires multiple lines of code or complex programmatic manipulation.
- Custom auth - handling specific authentication scenarios, such as getting authentication tokens from third-party APIs or checking if auth tokens need to be renewed.
- Cleanup scripts - executing specific cleanup code after every request in the test.
-
Working with XML - using the built-in
xml2jsonlibrary to create assertions or variables from an XML-based response body. - Debugging - running console logs for debugging purposes.
-
Contract testing - using the built-in
ajvlibrary to validate response body schemas and enforce the data contract.
This article explains how API snippets work, shows examples of common tasks, and lists the libraries you can use. To add a snippet to a request, flow, or test, see Adding snippets to API tests.
Use the low-code options in the API Test Editor for assertions and variables whenever you can, and save scripts for more complex scenarios. Tests with few scripts are easier for everyone in your workspace to understand and maintain, and their results are easier to read in the app.
How API snippets differ from browser snippets
API snippets are Postman-style scripts. They use the Postman pm object, which is available through the mabl integration with Postman, to read and set variables, inspect the response, and make assertions.
If you've written JavaScript snippets for browser tests, note these differences:
- API snippets don't use the
mablJavaScriptStep(mablInputs, callback)function. Write your code directly in the snippet. -
fetch()isn't available. To call another endpoint from a snippet, usepm.sendRequest(). - To read a test variable, use
pm.variables.get()instead ofmablInputs.
Types of custom scripts
You can add API snippets at three levels. To add one, see Adding snippets to API tests.
- Test-level scripts apply to every request in an API test.
- Flow-level scripts apply to every request in an API flow.
- Request-level scripts apply to the individual request.
For a given request, depending on the scripts that exist, the order of execution is as follows:
- Test-level pre-request script
- Flow-level pre-request script
- Request-level pre-request script
- Request
- Response
- Test-level post-request script
- Flow-level post-request script
- Request-level post-request script
Common tasks
These examples show how to do common tasks in an API snippet. For more on the pm object, see the Postman documentation on scripts.
Access variables
To use an existing variable from the test in an API snippet, use pm.variables.get(). For example:
// get the value of "new_user_id" and store in variable newUserId
let newUserId = pm.variables.get("new_user_id")
// log the value of newUserId to the console
console.log(`The new user's ID is ${newUserId}`);
To access flow parameters within a snippet, use pm.variables.replaceIn(). For example:
// get the value of "product_id" flow parameter and store in variable productId
let productId = pm.variables.replaceIn('{{flow.product_id}}')
// log the value of productId to the console
console.log(`The product ID is ${productId}`);
Validate a response
To validate a JSON body response, use pm.expect(). For example:
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);
// assert that the third person object in the response has the name in the variable "personName"
pm.expect(responseJson.person[3].name).to.eql(pm.variables.get("personName"));
// validate the length of an array
pm.expect(responseJson.person).to.have.lengthOf(15);
});
Create a variable
To create a variable based on a JSON response, use pm.environment.set(). For example:
var jsonData = JSON.parse(responseBody);
//assign the third person's object id to a variable named userID
pm.environment.set("userID", jsonData.person[3].id);
Run console logs
Console logs are useful for debugging. The following log statements are supported:
- console.log()
- console.info()
- console.warn()
- console.error()
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.
GenAI snippets
If you need help getting started with a custom API snippet, try describing what you want to do with the AI Snippet Generator. Your prompt may include references to test variables and request information. The AI Snippet Generator has access to the following information:
- The name of the step
- Variables in the test
- Request details, including the request method, URL, and headers
- Response details, including the response headers, body, status, and status code
The AI Snippet Generator masks the values of variables, request headers, and response headers that may contain sensitive data. For headers whose name contains “authorization” or “cookie” and variables whose name contains “password”, including the “api.credentials.password” variable, their values are hidden from the AI Snippet Generator.
Supported libraries
Thanks to the mabl integration with Postman, you can use Postman-supported JavaScript objects and functions to handle your custom logic and response validations.
The Postman integration also makes it possible to use a number of JavaScript libraries and Node.js modules:
JavaScript libraries
- ajv
- atob
- btoa
- chai
- cheerio
- crypto-js
- csv-parse/lib/sync
- lodash
- moment
- postman-collection
- tv4
- uuid
- xml2js
Node.js modules
- path
- assert
- buffer
- util
- url
- punycode
- querystring
- string-decoder
- stream
- timers
- events
You can use the require() method to call one of those libraries. Here is an example of using the moment library to generate a future date that is seven days from today.
let moment = require('moment');
//get a date that is N number of days from today
let date = moment.utc().add(7, 'days').toJSON();
//specify desired date and time format
let dateFormat = "MM-DD-YYYY"
//format the date and assign it to a variable to be used in other API requests and tests
pm.environment.set("futureDate", moment(date).format(dateFormat));
JavaScript version support
API snippets support JavaScript through ECMAScript 2024 (ES2024), including optional chaining (?.), nullish coalescing (??), and logical assignment (??=). Top-level await isn't supported. Use .then() or wrap the code in an async function instead.