### Install Selenium WebDriver Source: https://docs.requestly.com/http-interception/guides/intercepting-and-modifying-network-requests-in-web-automation-frameworks-like-selenium-and-playwright Install the Selenium WebDriver package for Node.js. ```bash npm install selenium-webdriver ``` -------------------------------- ### Example: Setting a User-Defined Variable Source: https://docs.requestly.com/api-client/environments-and-variables/dynamic-variables This example demonstrates how to set a user-defined environment variable. User-defined variables take precedence over dynamic variables with the same name. ```javascript rq.environment.set("$randomUUID", "123e4567-e89b-12d3-a456-426614174000"); ``` -------------------------------- ### Install Puppeteer Source: https://docs.requestly.com/http-interception/guides/intercepting-and-modifying-network-requests-in-web-automation-frameworks-like-selenium-and-playwright Install the Puppeteer package for Node.js. ```bash npm install puppeteer ``` -------------------------------- ### Select Xcode Installation Source: https://docs.requestly.com/http-interception/interceptor/desktop-app/ios-simulator-interception If the `xcrun simctl` command fails, use this command to explicitly set the path to your Xcode installation. This ensures Requestly can correctly locate and interact with your simulator. ```bash sudo xcode-select -s /Applications/Xcode.app ``` -------------------------------- ### Install Requestly Interceptor on Windows using Winget Source: https://docs.requestly.com/http-interception/getting-started/downloads Use this command in PowerShell or Command Prompt to install the Requestly Interceptor on Windows. ```bash winget install BrowserStackInc.Requestly ``` -------------------------------- ### Start BrowserStackLocal with Proxy Settings Source: https://docs.requestly.com/http-interception/guides/requestly-integration-browserstack-app-live Use this command to start the BrowserStack Local binary, configuring it to use the proxy settings provided by Requestly Interceptor. Ensure you replace placeholders with your actual access key and proxy details. ```bash ./ --key --local-proxy-host --local-proxy-port --force-proxy --force-local ``` -------------------------------- ### Install Playwright Source: https://docs.requestly.com/http-interception/guides/intercepting-and-modifying-network-requests-in-web-automation-frameworks-like-selenium-and-playwright Install the Playwright package for Node.js. ```bash npm install playwright ``` -------------------------------- ### Manual Proxy Setup via ADB Source: https://docs.requestly.com/http-interception/interceptor/desktop-app/android-simulator-interception Use this ADB command to manually set the HTTP proxy for an Android emulator, bypassing the emulator's UI. Ensure ADB is installed and the emulator is connected. ```bash adb shell settings put global http_proxy ":" ``` -------------------------------- ### JSON Data File Example Source: https://docs.requestly.com/api-client/collection-runner-data-file This is an example of a JSON file format. It must be an array of key-value objects, where each object defines one iteration. ```json [ { "city": "Vancouver", "temperature": 10 }, { "city": "Austin", "temperature": 24 }, { "city": "London", "temperature": 12 } ] ``` -------------------------------- ### Get All Rules cURL Example Source: https://docs.requestly.com/http-interception/public-apis/get-rule Use this cURL command to retrieve all rules associated with your Requestly Interceptor workspace. Ensure you replace 'your_api_key' with your actual API key. ```bash curl --request GET \ --url https://api2.requestly.io/v1/rules \ --header 'accept: application/json' \ --header 'x-api-key: your_api_key' ``` -------------------------------- ### Regex Examples for URL Matching Source: https://docs.requestly.com/http-interception/http-rules/advanced-usage/source-conditions These examples demonstrate how to use regex patterns in source conditions to match specific URLs. Ensure your regex patterns are valid and enclosed in slashes. ```regex /^https://.*github.*/ ``` ```regex /^https://blog\..*\.com$/ ``` ```regex /^((?!example).)*$/ ``` -------------------------------- ### Selenium Example: Add and Verify Request Header Source: https://docs.requestly.com/http-interception/guides/modify-http-headers-in-web-automation-using-requestly This example shows how to set up Selenium with the Requestly extension to add a custom request header and verify its presence on a target website. ```javascript const { Builder, By, until } = require("selenium-webdriver"); const chrome = require("selenium-webdriver/chrome"); const path = require("path"); (async () => { const options = new chrome.Options(); options.setChromeBinaryPath("/Path/to/chrome-for-testing"); options.addExtensions(path.resolve(__dirname, "requestly.crx")); const driver = await new Builder() .forBrowser("chrome") .setChromeOptions(options) .build(); // give Chrome a moment for any stray tabs await driver.sleep(500); // close any “welcome” tab if still present const handles = await driver.getAllWindowHandles(); const mainHandle = handles[0]; for (const handle of handles.slice(1)) { await driver.switchTo().window(handle); await driver.close(); } await driver.switchTo().window(mainHandle) try { await driver.get("https://app.requestly.io/automation/add-request-header?x-testing=selenium"); await driver.wait( until.elementTextContains( driver.findElement(By.tagName("body")), "Success" ), 1000 ); await driver.get("https://testheaders.com"); await driver.findElement(By.css("button")).click(); await driver.wait( until.elementTextContains( driver.findElement(By.tagName("body")), "x-testing" ), 5000 ); console.log("Header added and verified!"); } catch (err) { console.error("Error during automation:", err); } finally { await driver.quit(); } })(); ``` -------------------------------- ### Bulk Edit Headers Example Source: https://docs.requestly.com/api-client/send-api-request/create-requests/request-headers Manage multiple headers at once using the Bulk Edit feature. Each line represents a header in `key:value` format. Lines starting with `//` are disabled. ```text Content-Type:application/json Authorization:Bearer {{token}} X-API-Version:v2 // X-Debug:true ``` -------------------------------- ### Import Simple GET Request using cURL Source: https://docs.requestly.com/api-client/import-export/import-from-curl Paste a simple cURL GET request into the import dialog to convert it into an editable API request. ```bash curl https://api.example.com/users ``` -------------------------------- ### CSV Data File Example Source: https://docs.requestly.com/api-client/collection-runner-data-file This is an example of a CSV file format. The first row defines variable names, and each subsequent row represents one iteration. ```csv city,temperature Vancouver,10 Austin,24 London,12 ``` -------------------------------- ### Get Specific Rule cURL Example Source: https://docs.requestly.com/http-interception/public-apis/get-rule This cURL command demonstrates how to fetch details for a specific rule using its unique ID. Replace 'Redirect_a9qau' with the actual rule ID and 'your_api_key' with your API key. ```bash curl --request GET \ --url https://api2.requestly.io/v1/rules/Redirect_a9qau \ --header 'accept: application/json' \ --header 'x-api-key: your_api_key' ``` -------------------------------- ### Import GET Request with Headers and Query Param using cURL Source: https://docs.requestly.com/api-client/import-export/import-from-curl Import a cURL GET request that includes headers and query parameters. This demonstrates how Requestly handles these components. ```bash curl "https://api.example.com/users?page=2" \ --header "Authorization: Bearer YOUR_TOKEN" \ --header "Accept: application/json" ``` -------------------------------- ### Check Xcode Command-Line Tools Source: https://docs.requestly.com/http-interception/interceptor/desktop-app/ios-simulator-interception Run this command in the terminal to verify your Xcode command-line tools installation. If it returns an error, your Xcode installation might be misconfigured. ```bash xcrun simctl ``` -------------------------------- ### Development Environment Configuration Source: https://docs.requestly.com/http-interception/guides/community-content/variables-and-environments-in-requestly Set up environment-specific variables, such as the base URL and environment identifier, for your development setup. ```text base_url = https://jsonplaceholder.typicode.com environment = dev ``` -------------------------------- ### SOAP Request Body Example Source: https://docs.requestly.com/api-client/send-api-request/send-soap Construct the XML body for your SOAP request, including the Envelope and Body elements with appropriate namespaces. This example demonstrates an 'Add' operation. ```xml {{intA}} {{intB}} ``` -------------------------------- ### Store Default Values Source: https://docs.requestly.com/api-client/rq-api-reference/rq-collection-variables Example of setting default values that can be overridden by environment variables. ```APIDOC ## Store Default Values ### Description Set default values that can be overridden by environment variables. ### Request Example ```javascript // In pre-request script // const pageSize = rq.environment.get("pageSize") || // rq.collectionVariables.get("defaultPageSize") || // "20"; // console.log("Using page size:", pageSize); ``` ``` -------------------------------- ### Example of Compiled URL with Path Variables Source: https://docs.requestly.com/api-client/send-api-request/create-requests/parameters-and-body After setting values for detected path variables, Requestly compiles the URL with your provided data. ```text https://api.example.com/users/123/posts/456 ``` -------------------------------- ### Log Request Details Source: https://docs.requestly.com/api-client/scripts Example of using console.log within a script to inspect request details like method and URL at runtime. ```javascript console.log("Request Method:", rq.request.method); console.log("Request URL:", rq.request.url); ``` -------------------------------- ### Naming Convention Example Source: https://docs.requestly.com/api-client/rq-api-reference/rq-collection-variables Use descriptive names for collection variables to improve clarity and maintainability. ```javascript rq.collectionVariables.set("authBaseEndpoint", "/auth"); rq.collectionVariables.set("apiVersion", "v2"); ``` -------------------------------- ### Store API Base Path Source: https://docs.requestly.com/api-client/rq-api-reference/rq-collection-variables Example of setting a base path that all requests in the collection can use. ```APIDOC ## Store API Base Path ### Description Set a base path that all requests in the collection can use. ### Request Example ```javascript // In pre-request script // rq.collectionVariables.set("basePath", "/api/v2"); // rq.collectionVariables.set("apiVersion", "v2"); // Then use it in your request URL: // {{baseUrl}}{{basePath}} ``` ``` -------------------------------- ### Domains, Emails and Usernames Source: https://docs.requestly.com/api-client/environments-and-variables/dynamic-variables Generate random email addresses, example emails, usernames, and URLs. ```APIDOC ## $randomEmail ### Description Generates a random email address. ### Arguments - `firstName` (string): The first name to use. - `lastName` (string): The last name to use. - `provider` (string): The email provider (e.g., "gmail.com"). - `allowSpecialCharacters` (boolean): `true` to allow special characters, `false` otherwise. ### Example ``` {{$randomEmail "John"}} {{$randomEmail "John" "Doe" "gmail.com"}} ``` ## $randomExampleEmail ### Description Generates a random example email address (e.g., john.doe@example.com). ### Arguments - `firstName` (string): The first name to use. - `lastName` (string): The last name to use. - `allowSpecialCharacters` (boolean): `true` to allow special characters, `false` otherwise. ### Example ``` {{$randomExampleEmail "John" "Doe"}} ``` ## $randomUserName ### Description Generates a random username. ### Arguments - `firstName` (string): The first name to use. - `lastName` (string): The last name to use. ### Example ``` {{$randomUserName "John" "Doe"}} ``` ## $randomUrl ### Description Generates a random URL. ### Arguments - `protocol` (string): `http` or `https`. - `appendSlash` (boolean): `true` to append a trailing slash, `false` otherwise. ### Example ``` {{$randomUrl "https" "true"}} ``` ``` -------------------------------- ### Using Variables in Header Values Source: https://docs.requestly.com/api-client/send-api-request/create-requests/request-headers Dynamically set header values using variables. The example shows an `Authorization` header with a placeholder for a token. ```text Key: Authorization Value: Bearer {{authToken}} ``` -------------------------------- ### Global Timestamp Source: https://docs.requestly.com/api-client/rq-api-reference/rq-globals Record the start time of a test run as a global variable and calculate elapsed time in subsequent requests. ```javascript // Set once at the beginning of a test run rq.globals.set("testRunStartTime", Date.now()); // Reference in any request const startTime = rq.globals.get("testRunStartTime"); const elapsed = Date.now() - parseInt(startTime); console.log("Time since test start:", elapsed, "ms"); ``` -------------------------------- ### Common Dynamic Variables Source: https://docs.requestly.com/api-client/environments-and-variables/dynamic-variables Examples of common dynamic variables available in Requestly, including GUID, timestamps, and UUIDs. ```text {{$guid}} ``` ```text {{$timestamp}} ``` ```text {{$isoTimestamp}} ``` ```text {{$randomUUID}} ``` -------------------------------- ### Example: Importing multiple libraries Source: https://docs.requestly.com/api-client/import-packages-into-your-scripts Shows how to import 'moment', 'cheerio', and 'uuid' simultaneously. It then uses these libraries to generate an ID, format the time, and parse simple HTML. ```javascript const moment = require('moment'); const cheerio = require('cheerio'); const { v4: uuidv4 } = require('uuid'); const id = uuidv4(); const time = moment().format('HH:mm:ss'); const $ = cheerio.load('

Hello Requestly

'); console.log('Text:', $('h1').text()); console.log('Request ID:', id, 'Time:', time); ``` -------------------------------- ### Example: Importing moment and uuid Source: https://docs.requestly.com/api-client/import-packages-into-your-scripts Demonstrates importing the 'moment' library for date formatting and 'uuid' for generating unique IDs. Logs the current time and a generated ID to the console. ```javascript // Importing moment for date formatting const moment = require('moment'); const current = moment().format('YYYY-MM-DD HH:mm:ss'); console.log('Current Time:', current); // Importing uuid to generate unique IDs const { v4: uuidv4 } = require('uuid'); console.log('Generated ID:', uuidv4()); ``` -------------------------------- ### Get Rule Source: https://docs.requestly.com/llms.txt Learn how to retrieve all rules or specific ones using Requestly Interceptor's API with detailed examples. ```APIDOC ## Get Rule ### Description Learn how to retrieve all rules or specific ones using Requestly Interceptor's API with detailed examples. ### Method GET ### Endpoint /rules ### Query Parameters - **ruleId** (string) - Optional - The ID of the specific rule to retrieve. If omitted, all rules are returned. - **groupId** (string) - Optional - Filter rules by group ID. ### Response #### Success Response (200 OK) - **rules** (array) - An array of rule objects. Each object contains: - **id** (string) - The ID of the rule. - **name** (string) - The name of the rule. - **type** (string) - The type of the rule. - **pattern** (string) - The URL pattern. - **action** (object) - The action configuration. - **enabled** (boolean) - The enabled status. - **groupId** (string) - The group ID. ### Response Example (All Rules) ```json { "rules": [ { "id": "rule-abcde", "name": "Redirect Example", "type": "redirect", "pattern": "https://old.example.com/*", "action": { "type": "url-redirect", "value": "https://new.example.com/" }, "enabled": true, "groupId": "group-12345" }, { "id": "rule-fghij", "name": "Modify Header Example", "type": "modify-headers", "pattern": "https://api.example.com/*", "action": { "type": "modify-headers", "value": { "X-Custom-Header": "New Value" } }, "enabled": false, "groupId": "group-67890" } ] } ``` ### Response Example (Specific Rule) ```json { "rules": [ { "id": "rule-abcde", "name": "Redirect Example", "type": "redirect", "pattern": "https://old.example.com/*", "action": { "type": "url-redirect", "value": "https://new.example.com/" }, "enabled": true, "groupId": "group-12345" } ] } ``` ``` -------------------------------- ### Creating a Basic Test Source: https://docs.requestly.com/api-client/rq-api-reference/rq-test Demonstrates how to create a test with a name and a function containing assertions using rq.expect. ```APIDOC ## rq.test(name, function) ### Description Creates a test with a given name and a test function. The test function should contain assertions using `rq.expect`. ### Parameters * `name` (string): The name of the test (will be displayed in test results) * `function` (function): A function containing test assertions ### Request Example ```javascript // Test that the response status is 200 q.test("Response is successful", function() { rq.expect(rq.response.code).to.equal(200); }); // Test that response contains expected data q.test("Response has user data", function() { const data = rq.response.json(); rq.expect(data).to.have.property("id"); rq.expect(data).to.have.property("name"); }); ``` ``` -------------------------------- ### Get All Groups Source: https://docs.requestly.com/http-interception/public-apis/get-group Fetches a list of all groups with support for pagination. You can control the starting index and the number of results per page. ```APIDOC ## GET /v1/groups ### Description Fetches a list of all groups in your Requestly Interceptor account. Supports pagination. ### Method GET ### Endpoint https://api2.requestly.io/v1/groups ### Query Parameters - **offset** (Integer) - Optional - The index from where the results should start. Defaults to `0`. - **pageSize** (Integer) - Optional - The number of results to return. Maximum value is `75`. Defaults to `30`. ### Request Example ```bash curl --request GET \ --url https://api2.requestly.io/v1/groups \ --header 'accept: application/json' \ --header 'x-api-key: your_api_key' ``` ### Response #### Success Response (200) - **success** (Boolean) - Indicates if the request was successful. - **data** (Array) - An array of group objects. - **createdBy** (String) - The ID of the user who created the group. - **creationDate** (Integer) - The timestamp when the group was created. - **currentOwnerId** (String) - The ID of the current owner of the group. - **id** (String) - The unique identifier for the group. - **isFavourite** (Boolean) - Indicates if the group is marked as a favorite. - **lastModifiedBy** (String) - The ID of the user who last modified the group. - **modificationDate** (Integer) - The timestamp when the group was last modified. - **name** (String) - The name of the group. - **objectType** (String) - The type of the object, which is 'group'. - **status** (String) - The current status of the group (e.g., 'Inactive'). - **nextOffset** (Null or Integer) - The offset for the next page of results, or null if there are no more pages. - **total** (Integer) - The total number of groups available. #### Response Example ```json { "success": true, "data": [ { "createdBy": "IUAGkRiEx6XI0B6qCc82qbwroKX2", "creationDate": 1736059835086, "currentOwnerId": "IUAGkRiEx6XI0B6qCc82qbwroKX2", "id": "Group_qrszh", "isFavourite": false, "lastModifiedBy": "IUAGkRiEx6XI0B6qCc82qbwroKX2", "modificationDate": 1736059835086, "name": "Group", "objectType": "group", "status": "Inactive" }, ... ], "nextOffset": null, "total": 50 } ``` ### Response Codes - **200** - List of groups retrieved successfully. - **400** - Bad Request. - **401** - Unauthorized action. - **500** - Server error. ``` -------------------------------- ### Real-World Workflow: Authenticated API Requests Source: https://docs.requestly.com/http-interception/guides/community-content/variables-and-environments-in-requestly A complete workflow example demonstrating the use of global, environment, collection, and runtime variables for making authenticated API requests, including login and subsequent authenticated calls. ```javascript // Step 1: Login Request POST {{base_url}}{{auth_endpoint}}/login // Step 2: Store token (post-response script) const token = JSON.parse(rq.response.body).access_token; rq.environment.set("auth_token", token); // Step 3: Use token in subsequent requests GET {{base_url}}/users/me Headers: Authorization: Bearer {{auth_token}} ``` -------------------------------- ### Common Use Cases for Global Variables Source: https://docs.requestly.com/api-client/rq-api-reference/rq-globals Examples demonstrating how to use global variables for storing application version, tracking global state, user preferences, timestamps, feature flags, and constants. ```APIDOC ## Common Use Cases ### Store Application Version Keep track of the application or API version being tested: ```javascript // In setup script rq.globals.set("appVersion", "1.0.0"); rq.globals.set("apiVersion", "v2"); // In any request const version = rq.globals.get("appVersion"); console.log("Testing with app version:", version); ``` ### Track Global State Maintain state that needs to be shared across all collections: ```javascript // Track total requests made const totalRequests = parseInt(rq.globals.get("totalRequests") || "0"); q.globals.set("totalRequests", totalRequests + 1); console.log("Total requests made:", totalRequests + 1); ``` ### Store User Preferences Keep user preferences that apply globally: ```javascript q.globals.set("preferredLanguage", "en"); q.globals.set("dateFormat", "YYYY-MM-DD"); q.globals.set("timezone", "UTC"); ``` ### Global Timestamp Set a global timestamp that all requests can reference: ```javascript // Set once at the beginning of a test run q.globals.set("testRunStartTime", Date.now()); // Reference in any request const startTime = rq.globals.get("testRunStartTime"); const elapsed = Date.now() - parseInt(startTime); console.log("Time since test start:", elapsed, "ms"); ``` ### Feature Flags Implement global feature flags: ```javascript // Enable/disable features globally q.globals.set("enableLogging", "true"); q.globals.set("enableDebugMode", "false"); q.globals.set("useNewEndpoint", "true"); // Check flags in any request const debugMode = rq.globals.get("enableDebugMode") === "true"; if (debugMode) { console.log("Debug mode is enabled"); } ``` ### Store Common Constants Define constants that are used across all collections: ```javascript q.globals.set("MAX_PAGE_SIZE", "100"); q.globals.set("DEFAULT_PAGE_SIZE", "20"); q.globals.set("API_KEY_HEADER", "X-API-Key"); ``` ``` -------------------------------- ### Copy Setup Command for Node.js Server Source: https://docs.requestly.com/http-interception/interceptor/desktop-app/nodejs This command is used to set up the Requestly Interceptor for your Node.js server. Ensure you copy the exact command provided in the app, as it may vary based on port availability. ```bash <(curl -sS localhost:7040/tpsetup) ``` -------------------------------- ### Example GraphQL Request Payload Source: https://docs.requestly.com/http-interception/http-rules/advanced-usage/graphql-modify-request-response This is an example of a typical GraphQL request payload that includes an 'operationName' field. ```json POST { "operationName": "getUsers", "query": ` query getUsers { users { id email } } ` } ``` -------------------------------- ### Generate GUID with Version Argument Source: https://docs.requestly.com/api-client/environments-and-variables/dynamic-variables Generate a Globally Unique Identifier (GUID) by specifying the version (4 or 7). ```text {{$guid 7}} {{$guid 4 "2026-01-01"}} ``` -------------------------------- ### Generate Random Example Email Source: https://docs.requestly.com/api-client/environments-and-variables/dynamic-variables Use $randomExampleEmail to generate a random email address using the 'example.com' domain. Provide optional 'firstName', 'lastName', and 'allowSpecialCharacters' arguments. ```handlebars {{$randomExampleEmail "John" "Doe"}} ``` -------------------------------- ### Using Custom vs. Dynamic Variables Source: https://docs.requestly.com/api-client/environments-and-variables/variable-precedence Demonstrates how to use custom variables and dynamic variables in pre-request scripts, highlighting the difference in resolution. ```javascript // In pre-request script // This uses your custom variable if defined, otherwise falls back to dynamic const myTimestamp = "{{timestamp}}"; // This always generates a fresh dynamic timestamp const freshTimestamp = rq.$timestamp(); ``` -------------------------------- ### Sample Response for Get All Rules Source: https://docs.requestly.com/http-interception/public-apis/get-rule This is a sample JSON response when retrieving all rules. It includes details of a sample rule, pagination information, and total count. ```json { "success": true, "data": [ { "createdBy": "IUAGkRiEx6XI0B6qCc82qbwroKX2", "creationDate": 1735820120338, "currentOwnerId": "IUAGkRiEx6XI0B6qCc82qbwroKX2", "description": "hello ", "extensionRules": [ { "action": { "redirect": { "url": "https://www.bing.com/" }, "type": "redirect" }, "condition": { "excludedInitiatorDomains": [ "requestly.io" ], "excludedRequestDomains": [ "requestly.io" ], "isUrlFilterCaseSensitive": true, "urlFilter": "https://www.google.com/" } } ], "groupId": "", "id": "Redirect_a9qau", "isFavourite": false, "isSample": false, "lastModifiedBy": "IUAGkRiEx6XI0B6qCc82qbwroKX2", "modificationDate": 1735820120338, "name": "test", "objectType": "rule", "pairs": [ { "destination": "https://www.bing.com/", "destinationType": "url", "id": "8id6k", "source": { "key": "Url", "operator": "Contains", "value": "https://www.google.com/" } } ], "ruleType": "Redirect", "schemaVersion": "3.0.0", "status": "Inactive" } // ... other rules ], "total": 56, "nextOffset": 31, } ``` -------------------------------- ### Send a GET Request to Echo Server Source: https://docs.requestly.com/account/workspace/user-roles Use this URL to send a GET request and receive the same data back in the response. This is useful for testing basic request functionality. ```http https://app.requestly.io/echo ``` -------------------------------- ### POST /users Request Example Source: https://docs.requestly.com/api-client/send-api-request/create-requests/generate-client-code This section shows how to make a POST request to the /users endpoint with a JSON body and Bearer token in various languages. ```APIDOC ## POST /users ### Description This endpoint creates a new user. ### Method POST ### Endpoint https://api.example.com/users ### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email of the user. ### Request Example ```json { "name": "Jane Doe", "email": "jane@example.com" } ``` ### Headers - **Authorization**: Bearer YOUR_TOKEN - **Content-Type**: application/json ``` -------------------------------- ### Best Practices for Global Variables Source: https://docs.requestly.com/api-client/rq-api-reference/rq-globals Recommendations for effectively using global variables, including naming conventions, documentation, checking existence, initialization, cleanup, and type conversion. ```APIDOC ## Best Practices 1. **Use Sparingly**: Reserve global variables for truly global data. Prefer collection or environment variables when possible. 2. **Naming Convention**: Use clear, uppercase names for global constants ```javascript rq.globals.set("MAX_RETRY_ATTEMPTS", "5"); rq.globals.set("DEFAULT_TIMEOUT_MS", "30000"); ``` 3. **Document Purpose**: Comment your global variable usage ```javascript // Global feature flag for new API version rq.globals.set("useV2Api", "true"); ``` 4. **Check Existence**: Always verify a variable exists before using it ```javascript const value = rq.globals.get("myGlobalVar"); if (!value) { console.error("Global variable 'myGlobalVar' not set"); } ``` 5. **Initialize Early**: Set global variables in a dedicated setup script or request. 6. **Clean Up**: Remove globals that are no longer needed ```javascript rq.globals.unset("temporaryFlag"); ``` 7. **Type Conversion**: Remember values are stored as strings ```javascript const maxRetries = parseInt(rq.globals.get("maxRetries") || "3"); const enableFeature = rq.globals.get("enableFeature") === "true"; ``` ``` -------------------------------- ### cURL Request to Get Groups Source: https://docs.requestly.com/http-interception/public-apis/get-group Use this cURL command to make a GET request to the API endpoint for fetching groups. Remember to replace 'your_api_key' with your actual API key. ```bash curl --request GET \ --url https://api2.requestly.io/v1/groups \ --header 'accept: application/json' \ --header 'x-api-key: your_api_key' ``` -------------------------------- ### Launch Chrome with Requestly Extension (Java) Source: https://docs.requestly.com/http-interception/guides/intercepting-and-modifying-network-requests-in-web-automation-frameworks-like-selenium-and-playwright Configure ChromeOptions to specify the Chrome binary path and add the Requestly CRX extension for Java automation. ```java ChromeOptions options = new ChromeOptions(); options.setBinary("/Path/to/chrome-for-testing"); options.addExtensions(new File("/path/to/requestly.crx")); WebDriver driver = new ChromeDriver(options); // driver.get(...) to open pages ``` -------------------------------- ### Example: Validate Response Structure Source: https://docs.requestly.com/api-client/rq-api-reference/rq-expect This example demonstrates how to validate the structure of a JSON response. It checks if the response is an object, has specific properties like 'status' and 'data', and that 'data' is a non-empty array. ```javascript rq.test("Response has correct structure", function() { const data = rq.response.json(); rq.expect(data).to.be.an("object"); rq.expect(data).to.have.property("status"); rq.expect(data).to.have.property("data"); rq.expect(data.data).to.be.an("array").and.not.be.empty; }); ``` -------------------------------- ### Common Use Case: Access Response Headers Source: https://docs.requestly.com/api-client/rq-api-reference/rq-response Example script to iterate through all response headers and log each header's key and value. ```APIDOC ### Access Response Headers ```javascript rq.response.headers.forEach((header) => { console.log(`${header.key}: ${header.value}`); }); ``` ``` -------------------------------- ### Get Environment Variable Source: https://docs.requestly.com/api-client/rq-api-reference/rq-environment Retrieves the value of the specified environment variable. ```APIDOC ## `rq.environment.get(key)` ### Description Retrieves the value of the specified environment variable. ### Parameters #### Path Parameters - **key** (string) - Required - The name of the environment variable to retrieve ### Returns The value of the environment variable, or `undefined` if it doesn’t exist. ### Request Example ```javascript const token = rq.environment.get("authToken"); console.log("Token:", token); ``` ``` -------------------------------- ### Accessing Request URL Source: https://docs.requestly.com/api-client/rq-api-reference/rq-request Get the complete URL of the API request. ```APIDOC ## `rq.request.url` ### Description The full URL of the API request. ### Example ```javascript console.log("Request URL:", rq.request.url); ``` ``` -------------------------------- ### Get Collection Variable Source: https://docs.requestly.com/api-client/rq-api-reference/rq-collection-variables Retrieves the value of a specified collection variable. ```APIDOC ## `rq.collectionVariables.get(key)` ### Description Retrieves the value of the specified collection variable. ### Parameters #### Path Parameters - **key** (string) - Required - The name of the collection variable to retrieve ### Returns The value of the collection variable, or `undefined` if it doesn’t exist. ### Request Example ```javascript const path = rq.collectionVariables.get("basePath"); console.log("Collection Variable basePath:", path); ``` ``` -------------------------------- ### Staging Environment Configuration Source: https://docs.requestly.com/http-interception/guides/community-content/variables-and-environments-in-requestly Configure variables for your staging environment, including its specific base URL and environment name. ```text base_url = https://jsonplaceholder.org environment = staging ``` -------------------------------- ### Track Collection State Source: https://docs.requestly.com/api-client/rq-api-reference/rq-collection-variables Example of maintaining state across requests in a collection. ```APIDOC ## Track Collection State ### Description Maintain state across requests in a collection. ### Request Example ```javascript // Track if authentication has been completed // const isAuthenticated = rq.collectionVariables.get("isAuthenticated"); // if (!isAuthenticated) { // console.log("Need to authenticate first"); // rq.collectionVariables.set("isAuthenticated", "true"); // } ``` ``` -------------------------------- ### Get Request URL Source: https://docs.requestly.com/api-client/rq-api-reference/rq-request Obtain the complete URL for the current API request. ```javascript console.log("Request URL:", rq.request.url); ``` -------------------------------- ### Launch Chrome with Requestly Extension (Puppeteer - Node.js) Source: https://docs.requestly.com/http-interception/guides/modify-http-headers-in-web-automation-using-requestly Launch a Chrome browser with the Requestly extension using Puppeteer. This example shows how to specify the browser executable path and load the extension. ```javascript const puppeteer = require('puppeteer'); const path = require('path'); const extensionPath = path.resolve(__dirname, 'requestly'); // IF Using Our NPM Package @requestly/rq-automation const { getExtension } = require("@requestly/rq-automation"); const extensionPath = getExtension("unpacked"); // ----- const browser = await puppeteer.launch({ executablePath: "/Path/to/chrome-for-testing", headless: false, args: [ `--disable-extensions-except=${extensionPath}`, `--load-extension=${extensionPath}` ] }); const page = await browser.newPage(); // page.goto(...) next ``` -------------------------------- ### Clean Up Temporary Secrets Source: https://docs.requestly.com/api-client/rq-api-reference/rq-vault Example of removing a temporary secret from the vault once it is no longer required. ```javascript await rq.vault.unset("one-time-code"); ``` -------------------------------- ### Store Computed Values Source: https://docs.requestly.com/api-client/rq-api-reference/rq-collection-variables Example of calculating and storing values that multiple requests will use. ```APIDOC ## Store Computed Values ### Description Calculate and store values that multiple requests will use. ### Request Example ```javascript // In pre-request script // const timestamp = Date.now(); // const signature = generateSignature(timestamp); // Your custom function // rq.collectionVariables.set("requestTimestamp", timestamp); // rq.collectionVariables.set("requestSignature", signature); ``` ``` -------------------------------- ### Launch Browser with Requestly Extension (Puppeteer - Node.js) Source: https://docs.requestly.com/http-interception/guides/intercepting-and-modifying-network-requests-in-web-automation-frameworks-like-selenium-and-playwright Use Puppeteer to launch a Chrome instance with the Requestly extension. Specify the executable path and load the extension using command-line arguments. ```javascript const puppeteer = require('puppeteer'); const path = require('path'); const extensionPath = path.resolve(__dirname, 'requestly'); // IF Using Our NPM Package @requestly/rq-automation const { getExtension } = require("@requestly/rq-automation"); const extensionPath = getExtension("unpacked"); // ----- const browser = await puppeteer.launch({ executablePath: "/Path/to/chrome-for-testing", headless: false, args: [ `--disable-extensions-except=${extensionPath}`, `--load-extension=${extensionPath}` ] }); const page = await browser.newPage(); // page.goto(...) next ``` -------------------------------- ### Launch Browser with Requestly Extension (Playwright - Python) Source: https://docs.requestly.com/http-interception/guides/intercepting-and-modifying-network-requests-in-web-automation-frameworks-like-selenium-and-playwright Configure Playwright's sync API to launch a persistent Chromium context with the Requestly extension. Specify the path to the unpacked CRX folder. ```python from playwright.sync_api import sync_playwright path_to_ext = "./requestly" # path to unpacked CRX folder user_data_dir = "/tmp/user-data-dir" with sync_playwright() as pw: context = pw.chromium.launch_persistent_context( user_data_dir, channel="chromium", headless=False, args=[ f"--disable-extensions-except={path_to_ext}", f"--load-extension={path_to_ext}" ] ) page = context.new_page() # use page.goto(...) context.close() ``` -------------------------------- ### Storing Values for Later Use Source: https://docs.requestly.com/api-client/rq-api-reference/rq-test Demonstrates how to store values from a response using `rq.environment.set` for use in subsequent requests or tests. ```APIDOC ## Storing Values ### Description Values from a response can be stored in the environment for use in later requests or tests. ### Request Example ```javascript q.test("Response contains user ID", function() { const data = rq.response.json(); rq.expect(data).to.have.property("id"); // Store for use in subsequent requests rq.environment.set("userId", data.id); }); ``` ``` -------------------------------- ### rq.info.iteration Source: https://docs.requestly.com/api-client/rq-api-reference/rq-info Gets the current iteration index when running collections, or 0 for single requests. ```APIDOC ## rq.info.iteration ### Description Get the current iteration index when running a collection with the Collection Runner. The index is **0-based**. For single request executions, this value is `0`. ### Type `number` ### Example ```javascript console.log("Current iteration:", rq.info.iteration); // Output: Current iteration: 0 (first iteration) // Output: Current iteration: 2 (third iteration) ``` ``` -------------------------------- ### Get Query Parameters Source: https://docs.requestly.com/api-client/rq-api-reference/rq-request Access all query parameters of the request. Parameters are returned as an object. ```javascript console.log("Query Params:", JSON.stringify(rq.request.queryParams)); ```