API Monitoring & Testing: 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 request (e.g. generating signatures for authentication). You can directly assign to any of the request data (except for size_bytes).

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

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 http://docs.aws.amazon.com/AmazonS3/latest/dev/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" + 
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;

Next: Initial Script →