Skip to content

Commit e0fad04

Browse files
automate-testing-via-scripts-in-requestly
1 parent 43e91d9 commit e0fad04

File tree

3 files changed

+236
-0
lines changed

3 files changed

+236
-0
lines changed
Lines changed: 236 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,236 @@
1+
---
2+
title: Automate API Testing via Scripts in Requestly
3+
author: Mustafa Sayyed
4+
authorUrl: https://github.com/mustafa-sayyed
5+
date: 2025-11-13
6+
description: Learn how to automate repetitive API testing tasks using Requestly's powerful Pre-request and Post-response scripting features
7+
tags: [api-testing, scripting, testing]
8+
difficulty: beginner
9+
---
10+
11+
# Automate API Testing via Scripts in Requestly
12+
13+
## Introduction
14+
15+
While working on backend projects, I started noticing a pattern in my API testing workflow. A lot of time was going into small repetitive steps - adding authentication tokens, updating headers, checking response fields, and copying values from one request into another.
16+
17+
None of it was difficult, but it was slowing everything down.
18+
19+
When I started exploring Requestly's Pre-request and Post-response scripting feature, things changed. With a few small scripts, I was able to automate most of those repetitive steps and focus more on actual development and debugging instead of setup work.
20+
21+
In this article, I'll walk through what I learned, the examples I tried, and how you can use Requestly scripts to make your own API testing faster and more organized.
22+
23+
## Scripts?
24+
25+
Now, you may be questioning what these scripts are.
26+
27+
The Scripts are just functions written in JavaScript to customize and validate API requests, responses, dynamically inject headers, authentication tokens, and many more things you can do using scripts.
28+
29+
> In fact they have introduced a new amazing feature that we can use NPM Packages inside Scripts, I will talk about them later in this article.
30+
31+
**In Requestly**, Scripts allow you to customize requests before the request is sent ( Pre-Request Scripts ) and validate the response data after the request is executed ( Post-Request Scripts)
32+
33+
![Pre Request and Post Request Scripts](/images/guide-pre-and-post-scripts/scripts.png)
34+
35+
36+
Before diving deep into pre-request scripts and post-request scripts, let's understand the basics of Scripting.
37+
38+
## The Basics:
39+
40+
**rq**: rq is the base object that contains all the methods that you can use for testing, customizing APIs, and validating responses. The `rq` object is available in all pre-request and post-response scripts.
41+
42+
**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.
43+
44+
**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.
45+
46+
**rq.test**: The `rq.test` object allows you to write tests in your post-response scripts to validate API responses and ensure your APIs are working as expected. You can learn more about `rq.test` here.
47+
48+
**rq.expect**: Write assertions for API testing using the powerful Chai.js assertion library. Use it with `rq.test` to validate response data.
49+
50+
**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.
51+
52+
53+
## Console Logs in Scripts
54+
55+
You can even 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 console or in the Requestly Debug Console for the desktop app.
56+
57+
Let's now dive deep into the Pre and Post Request Scripts
58+
59+
---
60+
61+
## Pre-Request Scripts:
62+
63+
Pre-request scripts execute right before the API call hits the server. Use them to tweak headers, bodies, query params, or URLs based on logic, variables, or conditions.​
64+
65+
Access request details through rq.request and manage variables with rq.environment or rq.globals. Common uses include auth token injection and random data generation.
66+
67+
### Example 1: Automatically Inject Auth Tokens in Headers
68+
69+
One of the most annoying parts of API testing is dealing with authentication tokens.
70+
71+
When testing login or register APIs, the server typically returns an authentication token in the response. After that, for every protected API, you have to manually copy that token and paste it into the Authorization header again and again.
72+
73+
It's time-consuming, error-prone, and honestly… very frustrating.
74+
75+
With Requestly scripts, you can completely automate this process.
76+
77+
#### Step 1: Save Token from Login Response
78+
79+
In the Post-response Script of your login or register API, add:
80+
81+
```javascript
82+
// Save auth token in environment variable
83+
rq.environment.set("authToken", rq.response.json().accessToken);
84+
```
85+
86+
Now, whenever the login request succeeds, the token is automatically stored in Requestly's environment.
87+
88+
#### Step 2: Inject Token into Every Request Automatically
89+
90+
In the Pre-request Script of your protected APIs, add:
91+
92+
```javascript
93+
const token = rq.environment.get("authToken");
94+
rq.headers["Authorization"] = `Bearer ${token}`;
95+
```
96+
97+
Now every request automatically carries the correct authentication token - no manual copying, no mistakes, no wasted time.
98+
99+
### Example 2: Auto-Increment Pagination
100+
101+
For paginated APIs, increment a page counter automatically: Suppose your API looks like this, and you are using an environment variable to keep track of the page number
102+
103+
```
104+
https://api.example.com/users?page={{page_number}}
105+
```
106+
107+
Pre-request script:
108+
109+
```javascript
110+
const currentPage = rq.environment.get("page_number") || 0;
111+
rq.environment.set("page_number", currentPage + 1);
112+
```
113+
114+
Now, every time you hit Send, the page number increases automatically
115+
116+
---
117+
118+
## Post-Request Scripts:
119+
120+
Post-response scripts run after the server responds. This is where Requestly becomes incredibly powerful.
121+
122+
Post-response scripts allow you to:
123+
124+
- Inspect the response
125+
- Validate data
126+
- Log important values
127+
- Extract information for later requests
128+
- Automate multi-step API workflows
129+
130+
### Example 1: Validating API Responses Automatically
131+
132+
Instead of manually checking if an API succeeded, you can let Requestly do it for you.
133+
134+
Add this in the Post-response Script:
135+
136+
```javascript
137+
if (rq.response.status !== 200) {
138+
console.error("Request failed with status:", rq.response.status);
139+
}
140+
```
141+
142+
Now, whenever an API fails, you'll immediately see a clear error in the console.
143+
144+
### Example 2: Debugging APIs with Structured Logs
145+
146+
When an API behaves strangely, Post-response scripts become your debugger.
147+
148+
```javascript
149+
console.log("Status:", rq.response.status);
150+
console.log("Headers:", rq.response.headers);
151+
console.log("Body:", rq.response.body);
152+
```
153+
154+
This gives you a complete picture of what the server returned.
155+
156+
### Example 3: Advanced Testing with Assertions
157+
158+
Validate schemas and body paths:
159+
160+
```javascript
161+
rq.test("Status is OK", () => {
162+
rq.response.to.be.ok;
163+
});
164+
165+
rq.test("Valid user schema", () => {
166+
rq.response.to.have.jsonSchema({
167+
type: "object",
168+
required: ["id", "name"],
169+
properties: {
170+
id: { type: "number" },
171+
name: { type: "string" }
172+
}
173+
});
174+
});
175+
176+
rq.test("Correct user name", () => {
177+
rq.response.to.have.jsonBody("user.name", "John Doe");
178+
});
179+
```
180+
181+
---
182+
183+
## Use NPM Packages Inside Your Requestly Scripts
184+
185+
One feature that really surprised me while working with Requestly is that you're not limited to plain JavaScript. You can actually use popular NPM packages directly inside your scripts.
186+
187+
This opens up a lot of powerful possibilities - from generating fake data to validating complex formats.
188+
189+
Let's look at a simple but extremely useful example.
190+
191+
### Example: Generating Unique User IDs using uuid
192+
193+
Suppose you are testing a user creation API and every request needs a unique identifier.
194+
195+
Instead of manually typing random values, you can use the popular uuid package.
196+
197+
```javascript
198+
// Pre Request Script
199+
const { v4: uuidv4 } = require("uuid");
200+
201+
const userId = uuidv4();
202+
203+
rq.body = JSON.stringify({
204+
id: userId,
205+
name: "Test User",
206+
role: "admin"
207+
});
208+
```
209+
210+
Now, every time you send the request:
211+
212+
- a new unique ID is generated
213+
- automatically attached to the request body
214+
- without any manual effort
215+
216+
217+
## Use AI to generate Test Scripts
218+
Requestly recently introduced a new feature to generate tests scripts using AI.
219+
You can use AI to generate Pre-Request and Post-Response scripts by describing what you want.
220+
221+
Learn more about [AI Test Generation](https://docs.requestly.com/general/api-client/ai-test-generator)
222+
223+
![AI Generated Scripts](/images/guide-pre-and-post-scripts/ai-generate-scripts.gif)
224+
225+
226+
## Wrapping Up
227+
In this article, we explored how Requestly's Pre-request and Post-response scripting features can automate repetitive API testing tasks. By injecting authentication tokens, automating pagination, validating responses, and even using NPM packages like uuid, you can significantly speed up your workflow.
228+
229+
The best part is that these scripts are easy to set up and require only basic JavaScript knowledge. Once you start using them, you'll wonder how you ever managed without them.
230+
231+
232+
## Additional Resources
233+
234+
- Learn more about [Requestly Scripts](https://docs.requestly.com/general/api-client/scripts)
235+
- [Use NPM Packages in Requestly Scripts - YouTube](https://youtu.be/C21BaqCOxF0?si=46P7AVdl5dR5NPfC)
236+
- [Pre Scripts and Post Scripts in Requestly - YouTube](https://youtu.be/jh3Pu4XnbxQ?si=l0hkO0EoCIuxHdEZ)
1.3 MB
Loading
45.9 KB
Loading

0 commit comments

Comments
 (0)