Skip to main content

Scripts in Requestly allow you to extend and customize your API requests and responses dynamically using JavaScript. These scripts enable you to manipulate requests before they are sent (Pre-request scripts) or process responses after they are received (Post-response scripts). With access to the full request and response objects, you can achieve advanced automation, validations, and transformations.

Pre-Request Scripts

Pre-Request Scripts run before the API request is sent to the server. They allow you to modify request attributes, such as headers, body, query parameters, or even the URL. Pre Scripts are useful for adding authentication tokens, generating timestamps, or altering the request dynamically based on certain conditions. Let’s try to understand the workings of pre-script using easy-to-follow examples. Auto Increment Page Numbers Let’s assume you have an endpoint that takes page number as query parameter, we use environment variable {{page_number}} to get value of page number.
https://app.requestly.io/echo?page={{page_number}}
We can get current page number from environment variables and set it back with an increment.
rq.environment.set("page_number", rq.environment.get("page_number")+1);
Now every time you click the Send button of this request it would send incremented page number. Test APIs by Randomising Values During development hitting an API with new data every time can be a pain, we can use Pre-Script to randomise the values and call the same API without getting duplicate entry error. Let’s setup our request with body as follows:
POST: <https://app.requestly.io/echo>
{
	"name": "{{name}}",
	"email": "{{email}}",
	"phone_number": "{{phone_number}}"
}
We will use below pre-script to create random values and update them in environment variables.
var name = (+new Date).toString(36).slice(-5);
var phone = Math.round((Math.random())*(10**10));
rq.environment.set("name", name);
rq.environment.set("email", name+"@example.com");
rq.environment.set("phone_number", phone);
You can also use pre-script to generate access tokens, validate the requests, generate some random data for the request. You can also access elements of the request, collection variables and environment variables, checkout Requestly’s JavaScript API.

Post-Response Scripts

Post-Response Scripts run after the API response is received. They allow you to process response data, validate outputs, or log details for debugging. Post Scripts are useful for transforming the response body, validating response codes, or storing results for further use. Let’s try to understand the working of post script using easy to follow examples. Validate Response Code
if (rq.response.code !== 200) {
    console.error("Unexpected Response Code:", rq.response.code);
}
We can also fetch and set API Keys or auth tokens, id, and other data from response of an API and use it in other APIs. You can access elements of the request, response, collection variables and environment variables, checkout Requestly’s JavaScript API.

Viewing Console Logs from Scripts

You can use console.log() or console.error() in your Pre-Request and Post-Response Scripts to debug your logic and inspect values at runtime. The logs from these scripts are prefixed with #script for easy filtering and are visible directly in your browser’s Developer Tools Console (DevTools) or in the Requestly Debug Console for the desktop app.

For Browser App

1

Open Developer Tools

Open your browser’s Developer Tools Console using F12, Cmd + Option + J*,* or Ctrl + Shift + J. Logs from your Pre-Request and Post-Response Scripts will appear here in real time.
2

Filter Logs Using Keyword

In the console’s filter box, type or paste the keyword #script to view only Requestly script logs. This helps you isolate logs originating from your API client scripts.

For Desktop App

1

Open Debug Console

From the top menu bar, navigate to View → Debug Requestly to open the console window. All your Pre-Request and Post-Response Script logs will be displayed here.
2

Filter Logs Using Keyword

In the console’s search or filter box, enter #script to view logs generated from API client scripts. This allows you to quickly locate relevant log entries for debugging.

Requestly JavaScript API rq

Requestly provides a robust set of JavaScript properties and methods to interact with API requests, responses, environments, and global variables. The rq object is available in all pre-request and post-response scripts, giving you full control over your API workflow.

Available Objects

The Requestly JavaScript API consists of the following main objects:

rq.request

Access and manipulate API request details including method, headers, body, URL, and query parameters. Use this in both pre-request and post-response scripts to read or modify request data. Quick Example:
console.log("Request Method:", rq.request.method);
console.log("Request URL:", rq.request.url);
View complete rq.request documentation →

rq.response

Access API response details including body, headers, status code, and response time. Primarily used in post-response scripts to process and validate API responses. Quick Example:
console.log("Response Code:", rq.response.code);
const data = rq.response.json();
View complete rq.response documentation →

rq.environment

Manage environment-specific variables dynamically. Environment variables are scoped to a specific environment (dev, staging, production) and can be used across multiple requests. Quick Example:
rq.environment.set("authToken", "Bearer <TOKEN>");
const token = rq.environment.get("authToken");
View complete rq.environment documentation →

rq.collectionVariables

Manage collection-scoped variables. Collection variables are only accessible within requests that belong to a specific collection and persist across all environments. Quick Example:
rq.collectionVariables.set("basePath", "/v1/users");
const path = rq.collectionVariables.get("basePath");
View complete rq.collectionVariables documentation →

rq.globals

Manage global variables accessible across all collections and environments. Use for truly universal configuration and state. Quick Example:
rq.globals.set("appVersion", "1.0.0");
const version = rq.globals.get("appVersion");
View complete rq.globals documentation →

rq.test

Write tests to validate API responses and ensure your APIs work as expected. Tests help automate quality assurance in post-response scripts. Quick Example:
rq.test("Status code is 200", function() {
    rq.expect(rq.response.code).to.equal(200);
});
View complete rq.test documentation →

rq.expect

Write assertions for API testing using the powerful Chai.js assertion library. Use with rq.test to validate response data. Quick Example:
rq.test("Response has user data", function() {
    const data = rq.response.json();
    rq.expect(data).to.have.property("id");
    rq.expect(data.name).to.be.a("string");
});
View complete rq.expect documentation →

rq.info

Access execution metadata including request name, iteration index, and event name. Useful for tracking progress in collection runs and implementing iteration-specific logic. Quick Example:
console.log(`Running ${rq.info.requestName}`);
console.log(`Iteration ${rq.info.iteration + 1} of ${rq.info.iterationCount}`);
View complete rq.info documentation →

rq.iterationData

Access data from CSV or JSON files during collection runs. Each iteration receives different data from the file, enabling data-driven testing. Quick Example:
const city = rq.iterationData.get("city");
const temp = rq.iterationData.get("temperature");
console.log(`Weather in ${city}: ${temp}°C`);
View complete rq.iterationData documentation →

Variable Scope Hierarchy

When variables with the same name exist at multiple levels, the priority is: Environment Variables > Collection Variables > Global Variables This allows you to override global or collection defaults with environment-specific values.