In mabl, you can create custom scripts for API tests by combining one or more API snippets. Whenever possible, we recommend using our low-code functionality for creating assertions and variables. By limiting the use of custom snippets only to more complex scenarios, you can ensure that the results of your test are easy to view and maintain by all members of your workspace.
This article outlines how to accomplish several common tasks in an API snippet:
Many of these examples make use of the Postman JavaScript object, which is available through the mabl integration with Postman.
Working with XML payloads
For more information on writing scripts for SOAP APIs with XML payloads, click here.
Access variables
To use an existing variable from the test in an API snippet, use the pm.variables.get()
method. 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}`);
Validate a response
To validate a JSON body response, use the pm.expect()
method. 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 second person object in the response as the name properties of 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 the pm.environment.set()
method. 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.
Learn more
Refer to the Postman documentation for complete scripting reference for more information on Postman methods.