Using scripts in an API test can be useful in the following situations:
- Extracting data from a response in a specific way that requires multiple lines of code
- Handling specific authentication scenarios, such as getting authentication tokens from third party APIs or checking if auth tokens need to be renewed
- Executing specific cleanup code after every request in the test
- Creating assertions or variables from an XML-based response body
- Running console logs for debugging purposes
As a best practice, we recommend using the API Test Editor to write your tests whenever possible and limiting the use of Postman methods to handle more complex scenarios. Tests that don’t use, or make sparing use of, scripts are recommended for two reasons:
They are easier for all members of a workspace to understand and maintain.
Their results are easily viewable from the UI.
For working examples, see the API script examples guide.
Test size limits
Please note that API tests cannot exceed 1MB in size. We recommend using caution with large scripts.
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));
To learn how to add a script to a mabl API test, click here.
Updated 3 months ago