> ## Documentation Index
> Fetch the complete documentation index at: https://docs.requestly.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Pre-request & Post-response Scripts

> Learn how to use JavaScript in Requestly to customize API requests, process responses, and interact with variables, with examples.

***

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.

<iframe className="w-full aspect-video rounded-xl" src="https://www.youtube.com/embed/jh3Pu4XnbxQ" />

## **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.

<img src="https://mintcdn.com/requestly/xVEl1aB2iRcm03E4/images/script---1.png?fit=max&auto=format&n=xVEl1aB2iRcm03E4&q=85&s=6d058cc25b9a7aec0ee259a3280977cc" align="center" fullwidth="false" className="dark:hidden" width="2400" height="984" data-path="images/script---1.png" />

<img src="https://mintcdn.com/requestly/xVEl1aB2iRcm03E4/images/script---1-1.png?fit=max&auto=format&n=xVEl1aB2iRcm03E4&q=85&s=21364964b5f4d2d7d123cd9510f07ef3" align="center" fullwidth="false" className="hidden dark:block" width="2400" height="984" data-path="images/script---1-1.png" />

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.

```json theme={null}
https://app.requestly.io/echo?page={{page_number}}
```

We can get current page number from environment variables and set it back with an increment.

```json theme={null}
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:

```json theme={null}
POST: <https://app.requestly.io/echo>
```

```json theme={null}
{
	"name": "{{name}}",
	"email": "{{email}}",
	"phone_number": "{{phone_number}}"
}
```

We will use below pre-script to create random values and update them in environment variables.

```jsx theme={null}
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.

<img src="https://mintcdn.com/requestly/xVEl1aB2iRcm03E4/images/script---2.png?fit=max&auto=format&n=xVEl1aB2iRcm03E4&q=85&s=2debfb4b7f521a7f013e502f794c5fbf" align="center" fullwidth="false" className="dark:hidden" width="2400" height="1010" data-path="images/script---2.png" />

<img src="https://mintcdn.com/requestly/xVEl1aB2iRcm03E4/images/script---2-1.png?fit=max&auto=format&n=xVEl1aB2iRcm03E4&q=85&s=2f08ca250febdc7fe2f0d8d2caa8c5c2" align="center" fullwidth="false" className="hidden dark:block" width="2400" height="1010" data-path="images/script---2-1.png" />

Let’s try to understand the working of post script using easy to follow examples.

**Validate Response Code**

```jsx theme={null}
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.

<Steps>
  <Step title="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.
  </Step>

  <Step title="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.
  </Step>
</Steps>

## 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:**

```jsx theme={null}
console.log("Request Method:", rq.request.method);
console.log("Request URL:", rq.request.url);
```

[View complete rq.request documentation →](/api-client/rq-api-reference/rq-request)

***

#### `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:**

```jsx theme={null}
console.log("Response Code:", rq.response.code);
const data = rq.response.json();
```

[View complete rq.response documentation →](/api-client/rq-api-reference/rq-response)

***

#### `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:**

```jsx theme={null}
rq.environment.set("authToken", "Bearer <TOKEN>");
const token = rq.environment.get("authToken");
```

[View complete rq.environment documentation →](/api-client/rq-api-reference/rq-environment)

***

#### `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:**

```jsx theme={null}
rq.collectionVariables.set("basePath", "/v1/users");
const path = rq.collectionVariables.get("basePath");
```

[View complete rq.collectionVariables documentation →](/api-client/rq-api-reference/rq-collection-variables)

***

#### `rq.globals`

Manage global variables accessible across all collections and environments. Use for truly universal configuration and state.

**Quick Example:**

```jsx theme={null}
rq.globals.set("appVersion", "1.0.0");
const version = rq.globals.get("appVersion");
```

[View complete rq.globals documentation →](/api-client/rq-api-reference/rq-globals)

***

#### `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:**

```jsx theme={null}
rq.test("Status code is 200", function() {
    rq.expect(rq.response.code).to.equal(200);
});
```

[View complete rq.test documentation →](/api-client/rq-api-reference/rq-test)

***

#### `rq.expect`

Write assertions for API testing using the powerful Chai.js assertion library. Use with `rq.test` to validate response data.

**Quick Example:**

```jsx theme={null}
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 →](/api-client/rq-api-reference/rq-expect)

#### `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:**

```jsx theme={null}
console.log(`Running ${rq.info.requestName}`);
console.log(`Iteration ${rq.info.iteration + 1} of ${rq.info.iterationCount}`);
```

[View complete rq.info documentation →](/api-client/rq-api-reference/rq-info)

***

#### `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:**

```jsx theme={null}
const city = rq.iterationData.get("city");
const temp = rq.iterationData.get("temperature");
console.log(`Weather in ${city}: ${temp}°C`);
```

[View complete rq.iterationData documentation →](/api-client/rq-api-reference/rq-iteration-data)

***

### Using Dynamic Variables in Scripts

Requestly provides dynamic variables, which are built in values that automatically generate common data such as timestamps, UUIDs, and random values. You can access them in scripts using the rq.\$variableName() syntax.

**Quick Example:**

```jsx theme={null}
const uniqueId = rq.$randomUUID();
const timestamp = rq.$timestamp();
const email = rq.$randomEmail();

console.log("Generated User ID:", uniqueId);
console.log("Request Timestamp:", timestamp);
```

**Common Dynamic Variables:**

* `rq.$randomUUID()` - Generate unique identifiers
* `rq.$timestamp()` - Current Unix timestamp
* `rq.$isoTimestamp()` - ISO 8601 timestamp
* `rq.$randomInt()` - Random integer
* `rq.$randomEmail()` - Random email address
* `rq.$randomFirstName()` - Random first name
* `rq.$randomCompanyName()` - Random company name

**With Arguments:**

```jsx theme={null}
// Generate random integer between 1-100
const age = rq.$randomInt(1, 100);

// Generate alphanumeric string of length 10
const code = rq.$randomAlphaNumeric(10);

// Generate password with specific length
const password = rq.$randomPassword("20");

// Generate email with custom name
const email = rq.$randomEmail("John", "Doe");
```

[View complete Dynamic Variables documentation →](/api-client/environments-and-variables/dynamic-variables)
