Pre-request Scripts

Pre-request Scripts give you a chance to modify the request after variables have been resolved, but before the request is made. You can use this script to do any last minute processing like adding additional headers or parameters to your shared environment, test, or test step. You can directly assign to any of the request data (except for size_bytes).

If you directly update request.url or request.body this will take precedence over request.params and request.form respectively.

Pre-Request Script Ordering

Defining pre-request scripts at the shared environment or environment level enables these scripts to run automatically for every Request test step. However, pre-request scripts are only applicable to Request test steps and do not work with other step types like Incoming Request or Condition.

If you set pre-request scripts at different levels (such as shared environment, test, or step), none of the scripts will be overwritten. Instead, they will execute in the following order:

  • Shared Environment Pre-Request Scripts

  • Environment (Test Settings) Pre-Request Scripts

  • Test Step Pre-Request Scripts

Example - Adding/Editing URL Parameters

// Add a new querystring parameter ?foo=bar
request.params.push({name:"foo", value: "bar"});
// request.params is an array because we want to preserve the ordering of elements,
// but we also support and convert a dict/hash/object
request.params = {};
request.params["foo"] = "bar";

Example - Adding a Custom Header

var scheme = request.scheme;
var path = request.path;
// Add a new custom header that is the concatenation of the request
// scheme and path
request.headers["Custom-Header"] = scheme + " - " + path;

Example - S3 Authentication

This example will automatically sign and authorize S3 requests for URLs that are private S3 resources. Just use the editor to make a request to a private S3 url (e.g. GET https://s3.amazonaws.com/bucket-name/filename.txt) and add this Pre-request Script to add authentication.

// See https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html
// for an explaination of the S3 authentication scheme
// This script requires you to define the following initial variables
//     SecretAccessKeyId
//     AWSAccessKeyId

var date = moment().format("ddd, DD MMM YYYY HH:mm:ss ZZ");
var data = request.method + "\n" +
    "" + "\n" +                     // content-md5 is "" for GET requests
    "" + "\n" +                     // content-type is "" for GET requests
    date + "\n" + 
    request.path;
        
var hash = CryptoJS.HmacSHA1(data, variables.get("SecretAccessKeyId"));
var signature = hash.toString(CryptoJS.enc.Base64);
// Build the auth header    
var auth = "AWS " + variables.get("AWSAccessKeyId") + ":" + signature;
request.headers["Authorization"] = auth;
request.headers["Date"] = date;