### Run Local Development Server with Mintlify CLI Source: https://github.com/requestly/requestly-docs/blob/master/README.md This command starts the local development server for the Requestly documentation using the Mintlify CLI. Ensure you have Mintlify CLI installed and have navigated into the project directory. The documentation will be accessible at http://localhost:3000. ```bash mint dev ``` -------------------------------- ### Bulk Edit Headers Example Source: https://github.com/requestly/requestly-docs/blob/master/general/api-client/send-api-request/create-requests/request-headers.mdx Demonstrates how to add or update multiple headers at once using a key:value format. Lines starting with '//' are treated as comments and disabled. This is useful for managing headers efficiently, especially when copying from documentation. ```text Content-Type:application/json Authorization:Bearer {{token}} X-API-Version:v2 // X-Debug:true ``` -------------------------------- ### GraphQL Mutation Example Source: https://github.com/requestly/requestly-docs/blob/master/guides/community-content/using-graphql-in-requestly.mdx Illustrates a GraphQL mutation for creating a new post. This example shows how to send data to the server to modify resources. ```graphql mutation { createPost(title: "Hello", body: "World") { id title } } ``` -------------------------------- ### Manual Proxy Setup via ADB for Android Emulators Source: https://github.com/requestly/requestly-docs/blob/master/general/http-interceptor/desktop-app/android-simulator-interception.mdx This command-line instruction configures the HTTP proxy settings for an Android emulator using ADB. It requires ADB to be installed and assumes the user will replace placeholders with their actual IP and port. ```bash adb shell settings put global http_proxy ":" ``` -------------------------------- ### GraphQL Query Example Source: https://github.com/requestly/requestly-docs/blob/master/guides/community-content/using-graphql-in-requestly.mdx Demonstrates a basic GraphQL query to retrieve user data, including their posts. This example showcases fetching nested data structures. ```graphql query { user(id: 1) { name email } } ``` -------------------------------- ### Install Requestly on Windows using Winget Source: https://github.com/requestly/requestly-docs/blob/master/general/getting-started/downloads.mdx This command allows users to install Requestly on Windows machines using the Winget package manager. It is executed in PowerShell or Command Prompt. ```bash winget install BrowserStackInc.Requestly ``` -------------------------------- ### Install Automation Tools (npm) Source: https://github.com/requestly/requestly-docs/blob/master/guides/intercepting-and-modifying-network-requests-in-web-automation-frameworks-like-selenium-and-playwright.mdx Installs the necessary npm packages for popular browser automation tools: Selenium WebDriver, Playwright, and Puppeteer. These are essential for controlling browser instances programmatically. ```bash npm install selenium-webdriver ``` ```javascript npm install playwright ``` ```javascript npm install puppeteer ``` -------------------------------- ### GET /v1/rules - Get All Rules Source: https://context7.com/requestly/requestly-docs/llms.txt Retrieves all rules in the workspace with pagination support. ```APIDOC ## GET /v1/rules - Get All Rules ### Description Retrieves all rules in the workspace with pagination support. Returns rule details including type, status, and configuration. ### Method GET ### Endpoint https://api2.requestly.io/v1/rules ### Parameters #### Query Parameters - **offset** (integer) - Optional - The number of rules to skip (for pagination). - **pageSize** (integer) - Optional - The maximum number of rules to return per page. #### Headers - **accept** (string) - Required - `application/json` - **x-api-key** (string) - Required - Your Requestly API key ### Request Example ```bash curl --request GET \ --url 'https://api2.requestly.io/v1/rules?offset=0&pageSize=30' \ --header 'accept: application/json' \ --header 'x-api-key: YOUR_API_KEY' ``` ### Response #### Success Response (200 OK) Returns a JSON object containing a list of rules, total count, and the next offset for pagination. #### Response Example ```json { "success": true, "data": [ { "id": "Redirect_a9qau", "name": "test", "ruleType": "Redirect", "status": "Inactive", "pairs": [...] } ], "total": 56, "nextOffset": 31 } ``` ``` -------------------------------- ### Get and Check Global Variables in Requestly Source: https://github.com/requestly/requestly-docs/blob/master/general/api-client/rq-api-reference/rq-globals.mdx Illustrates how to retrieve and validate the existence of global variables using `rq.globals.get`. It includes an example of logging an error if a variable is not found, preventing potential runtime issues. ```jsx const value = rq.globals.get("myGlobalVar"); if (!value) { console.error("Global variable 'myGlobalVar' not set"); } ``` -------------------------------- ### x-www-form-urlencoded Body Example Source: https://github.com/requestly/requestly-docs/blob/master/general/api-client/send-api-request/create-requests/parameters-and-body.mdx Example of data formatted as URL-encoded key-value pairs, typically used for traditional web form submissions. ```plaintext username=johndoe password=secret123 remember=true ``` -------------------------------- ### RAW JSON Body Example Source: https://github.com/requestly/requestly-docs/blob/master/general/api-client/send-api-request/create-requests/parameters-and-body.mdx Example of sending structured JSON data as a request body. This is commonly used for REST API payloads. ```json { "name": "John Doe", "email": "john@example.com", "age": 30, "active": true } ``` -------------------------------- ### Set and Get Environment Variables - JavaScript Source: https://context7.com/requestly/requestly-docs/llms.txt Demonstrates how to set and retrieve environment variables within scripts using the `rq.environment` object. These variables can be used across requests with `{{variable_name}}` syntax. Supports setting, getting, and using variables in request URLs. ```javascript // Setting environment variables in scripts rq.environment.set("base_url", "https://api.example.com"); rq.environment.set("authToken", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."); rq.environment.set("user_id", "123"); // Getting environment variables const baseUrl = rq.environment.get("base_url"); const token = rq.environment.get("authToken"); // Using variables in request URL: // https://{{base_url}}/users/{{user_id}} // Resolves to: https://api.example.com/users/123 // Using collection variables rq.collectionVariables.set("basePath", "/v1/users"); const path = rq.collectionVariables.get("basePath"); // Using global variables (accessible across all collections) rq.globals.set("appVersion", "1.0.0"); const version = rq.globals.get("appVersion"); ``` -------------------------------- ### Commit Changes (Bash) Source: https://github.com/requestly/requestly-docs/blob/master/guides/community-content/README.md Shows the commands to stage all changes and commit them with a descriptive message, following the recommended format for contributions. ```bash git add . git commit -m "Add: [Your Tutorial Title]" ``` -------------------------------- ### Using Variables in API Request Headers (Example) Source: https://github.com/requestly/requestly-docs/blob/master/guides/community-content/variables-and-environments-in-requestly.mdx This example illustrates the use of variables within API request headers. It shows how to dynamically set headers such as `Authorization`, `Content-Type`, and custom headers like `X-API-Key` using variable placeholders. ```plaintext Authorization: Bearer {{auth_token}} Content-Type: {{content_type}} X-API-Key: {{api_key}} ``` -------------------------------- ### Create a Redirect Rule Source: https://context7.com/requestly/requestly-docs/llms.txt Creates a new HTTP Redirect rule in Requestly. This example shows how to redirect all requests to 'https://www.google.com/' to 'https://www.bing.com/'. ```bash # Create a Redirect Rule curl --request POST \ --url https://api2.requestly.io/v1/rules \ --header 'accept: application/json' \ --header 'content-type: application/json' \ --header 'x-api-key: YOUR_API_KEY' \ --data '{ "objectType": "rule", "ruleType": "Redirect", "status": "Active", "name": "Redirect Google to Bing", "description": "Redirects all Google requests to Bing", "pairs": [ { "destinationType": "url", "source": { "value": "https://www.google.com/", "operator": "Equals", "key": "Url" }, "destination": "https://www.bing.com/" } ] }' ``` -------------------------------- ### JavaScript Workflow Example for API Authentication with Requestly Variables Source: https://github.com/requestly/requestly-docs/blob/master/guides/community-content/variables-and-environments-in-requestly.mdx This JavaScript snippet illustrates a complete API workflow using Requestly's variable system. It shows how to make a login request, capture an authentication token from the response using a post-response script, store it as a runtime variable, and then utilize this token in subsequent authenticated requests. This example leverages global variables (implicitly via `{{base_url}}`), environment variables (implicitly via `{{base_url}}`), and runtime variables (`auth_token`). ```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; q.environment.set("auth_token", token); // Step 3: Use token in subsequent requests GET {{base_url}}/users/me Headers: Authorization: Bearer {{auth_token}} ``` -------------------------------- ### Clone Requestly Docs Repository Source: https://github.com/requestly/requestly-docs/blob/master/README.md This command clones the Requestly documentation repository from GitHub. It requires Git to be installed on your system. After cloning, you navigate into the newly created directory. ```bash git clone https://github.com/requestly/requestly-docs.git cd requestly-docs ``` -------------------------------- ### Launching Browser with Requestly Extension Source: https://github.com/requestly/requestly-docs/blob/master/guides/modify-http-headers-in-web-automation-using-requestly.mdx Examples for launching browsers with the Requestly extension loaded using Playwright, Puppeteer, and Selenium. ```APIDOC ## Launching Browser with Requestly Extension ### Description Examples for launching browsers with the Requestly extension loaded using Playwright, Puppeteer, and Selenium. ### Playwright ```python from playwright.sync_api import sync_playwright user_data_dir = "/tmp/user-data-dir" path_to_ext = "/path/to/your/requestly/extension" 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() ``` ### Puppeteer ```javascript const puppeteer = require('puppeteer'); const path = require('path'); // IF Using Our NPM Package @requestly/rq-automation // const { getExtension } = require("@requestly/rq-automation"); // const extensionPath = getExtension("unpacked"); // ----- const extensionPath = path.resolve(__dirname, 'requestly'); // Replace with your extension path const browser = await puppeteer.launch({ executablePath: "/Path/to/chrome-for-testing", // Replace with your Chrome executable path headless: false, args: [ `--disable-extensions-except=${extensionPath}`, `--load-extension=${extensionPath}` ] }); const page = await browser.newPage(); // page.goto(...) next ``` ``` -------------------------------- ### Create a Delay Rule Source: https://context7.com/requestly/requestly-docs/llms.txt Creates a rule to introduce artificial latency to network requests. This example adds a 4000ms (4 second) delay to requests targeting 'api.example.com/products'. ```bash # Create a Delay Rule (4 second delay) curl --request POST \ --url https://api2.requestly.io/v1/rules \ --header 'accept: application/json' \ --header 'content-type: application/json' \ --header 'x-api-key: YOUR_API_KEY' \ --data '{ "objectType": "rule", "ruleType": "Delay", "status": "Active", "name": "Simulate Slow API", "pairs": [ { "source": { "key": "Url", "operator": "Contains", "value": "api.example.com/products" }, "delay": 4000 } ] }' ``` -------------------------------- ### Get All Rules with Pagination (curl) Source: https://context7.com/requestly/requestly-docs/llms.txt Retrieves all rules within a workspace, supporting pagination to handle large numbers of rules. The response includes rule details and pagination metadata. ```bash # Get all rules with pagination curl --request GET \ --url 'https://api2.requestly.io/v1/rules?offset=0&pageSize=30' \ --header 'accept: application/json' \ --header 'x-api-key: YOUR_API_KEY' # Response: # { # "success": true, # "data": [ # { # "id": "Redirect_a9qau", # "name": "test", # "ruleType": "Redirect", # "status": "Inactive", # "pairs": [...] # } # ], # "total": 56, # "nextOffset": 31 # } ``` -------------------------------- ### Staging Environment Configuration in Requestly Source: https://github.com/requestly/requestly-docs/blob/master/guides/community-content/variables-and-environments-in-requestly.mdx Provides an example of environment-specific variables for a 'Staging' environment in Requestly. This configuration sets the base URL for the staging API and an environment identifier. ```plaintext base_url = https://jsonplaceholder.org environment = staging ``` -------------------------------- ### Set and Get Shared State Variables in JavaScript Source: https://github.com/requestly/requestly-docs/blob/master/general/http-rules/advanced-usage/shared-state.mdx Provides examples of how to set and retrieve values from the $sharedState object in JavaScript. This is a fundamental operation for managing shared data across Requestly rules. ```jsx $sharedState.myVariable = "some value"; ``` ```jsx let myValue = $sharedState.myVariable; ``` -------------------------------- ### Launch Browser with Requestly Extension Source: https://github.com/requestly/requestly-docs/blob/master/guides/intercepting-and-modifying-network-requests-in-web-automation-frameworks-like-selenium-and-playwright.mdx Demonstrates how to launch a browser instance with the Requestly extension loaded. This is crucial for enabling Requestly's features within your automated sessions. It requires specifying the path to the unpacked extension. ```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() ``` ```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 ``` -------------------------------- ### Create New Content File (Bash) Source: https://github.com/requestly/requestly-docs/blob/master/guides/community-content/README.md Demonstrates how to create a new Markdown or MDX file for community content within the specified directory using the 'touch' command. ```bash cd guides/community-content # Create your content file (use .md or .mdx format) touch your-tutorial-name.mdx ``` -------------------------------- ### Configure Playwright with Requestly Extension (JavaScript) Source: https://github.com/requestly/requestly-docs/blob/master/guides/intercepting-and-modifying-network-requests-in-web-automation-frameworks-like-selenium-and-playwright.mdx Illustrates how to launch Playwright's Chromium browser with the Requestly extension loaded. It shows how to use `launchPersistentContext` and pass arguments to load the extension, including using the `@requestly/rq-automation` package. ```javascript const { chromium } = require('playwright'); const path = require('path'); // Assuming 'requestly' is an unpacked CRX folder in the same directory // const extensionPath = path.resolve(__dirname, 'requestly'); // IF Using Our NPM Package @requestly/rq-automation // const { getExtension } = require("@requestly/rq-automation"); // const extensionPath = getExtension("unpacked"); // ----- // Placeholder for the actual unpacked extension path const extensionPath = './path/to/unpacked/requestly'; const userDataDir = './user-data'; // Directory for persistent user data async function setupPlaywright() { const browser = await chromium.launch({ headless: false, // Set to true only if you handle '--headless=new' args: [ `--disable-extensions-except=${extensionPath}`, `--load-extension=${extensionPath}`, '--no-sandbox', '--disable-setuid-sandbox' ] }); // Using launchPersistentContext to ensure extension is loaded correctly const context = await chromium.launchPersistentContext(userDataDir, { channel: "chromium", // Required for extension loading in some versions headless: false, args: [ `--disable-extensions-except=${extensionPath}`, `--load-extension=${extensionPath}`, '--no-sandbox', '--disable-setuid-sandbox' ] }); const page = await context.newPage(); console.log("Playwright browser context initialized with Requestly extension."); // Now use page.goto() etc. // await context.close(); } setupPlaywright(); ``` -------------------------------- ### GET /v1/rules/{ruleId} - Get Specific Rule Source: https://context7.com/requestly/requestly-docs/llms.txt Retrieves details of a specific rule by its unique ID. ```APIDOC ## GET /v1/rules/{ruleId} - Get Specific Rule ### Description Retrieves details of a specific rule by its unique ID. ### Method GET ### Endpoint https://api2.requestly.io/v1/rules/{ruleId} ### Parameters #### Path Parameters - **ruleId** (string) - Required - The unique identifier of the rule to retrieve. #### Headers - **accept** (string) - Required - `application/json` - **x-api-key** (string) - Required - Your Requestly API key ### Request Example ```bash curl --request GET \ --url https://api2.requestly.io/v1/rules/Redirect_a9qau \ --header 'accept: application/json' \ --header 'x-api-key: YOUR_API_KEY' ``` ### Response #### Success Response (200 OK) Returns a JSON object containing the details of the specified rule. #### Response Example ```json { "success": true, "data": { "id": "Redirect_a9qau", "name": "test", "ruleType": "Redirect", "status": "Inactive", "pairs": [ { "destination": "https://www.bing.com/", "destinationType": "url" } ] } } ``` ``` -------------------------------- ### Configure Selenium with Requestly Extension (Java) Source: https://github.com/requestly/requestly-docs/blob/master/guides/intercepting-and-modifying-network-requests-in-web-automation-frameworks-like-selenium-and-playwright.mdx Provides a Java example for configuring Selenium's ChromeDriver. It specifies the path to the Chrome for Testing executable and adds the Requestly CRX extension, preparing the browser for automated testing with Requestly. ```java import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import java.io.File; public class SeleniumRequestly { public static void main(String[] args) { // Set the path to the ChromeDriver executable if not in PATH // System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver"); ChromeOptions options = new ChromeOptions(); options.setBinary("/Path/to/chrome-for-testing"); // Ensure the path to the CRX file is correct options.addExtensions(new File("/path/to/requestly.crx")); WebDriver driver = new ChromeDriver(options); System.out.println("Selenium driver initialized with Requestly extension."); // driver.get(...) to open pages // driver.quit(); } } ``` -------------------------------- ### Set Up Environment Variables in Requestly Source: https://github.com/requestly/requestly-docs/blob/master/general/api-client/quick-start.mdx Demonstrates how to define and use environment variables within Requestly to manage different API environments (e.g., dev, staging, production). Variables are referenced using double curly braces. ```text Key: base_url Value: https://jsonplaceholder.typicode.com Key: api_token Value: your_dev_token_here {{base_url}}/users/1 ``` -------------------------------- ### Configure Selenium with Requestly Extension (JavaScript) Source: https://github.com/requestly/requestly-docs/blob/master/guides/intercepting-and-modifying-network-requests-in-web-automation-frameworks-like-selenium-and-playwright.mdx Demonstrates how to configure a Selenium WebDriver instance in Node.js to use Chrome for Testing and load the Requestly CRX extension. It shows both manual path specification and using the `@requestly/rq-automation` package. ```javascript const { Builder } = require("selenium-webdriver"); const chrome = require("selenium-webdriver/chrome"); const path = require("path"); // Assuming 'requestly.crx' is in the same directory or specify the correct path // For unpacked CRX folder, use the folder path instead of .crx file // const extensionPath = path.resolve(__dirname, 'requestly.crx'); // IF Using Our NPM Package @requestly/rq-automation // const { getExtension } = require("@requestly/rq-automation"); // const extensionPath = getExtension("crx"); // or getExtension("unpacked") // ----- // Placeholder for the actual extension path const extensionPath = "/path/to/your/requestly.crx"; // or unpacked folder path const options = new chrome.Options(); options.setChromeBinaryPath("/Path/to/chrome-for-testing"); options.addExtensions(extensionPath); async function setupSelenium() { const driver = await new Builder() .forBrowser("chrome") .setChromeOptions(options) .build(); console.log("Selenium driver initialized with Requestly extension."); // Now use driver.get() to navigate as needed... // await driver.quit(); } setupSelenium(); ``` -------------------------------- ### Run BrowserStack Local Binary with Proxy Settings Source: https://github.com/requestly/requestly-docs/blob/master/guides/requestly-integration-browserstack-app-live.mdx This command initiates the BrowserStack Local binary, enabling it to proxy network traffic. It requires your BrowserStack access key and the IP/port configured in Requestly for proxying. Ensure you replace placeholders with your actual credentials and proxy details. ```powershell ./ --key --local-proxy-host --local-proxy-port --force-proxy --force-local ``` -------------------------------- ### Get Group Source: https://github.com/requestly/requestly-docs/blob/master/public-apis/get-group.mdx Retrieve details of specific groups or all groups using Requestly's API. This endpoint allows fetching a list of all groups in your Requestly account and supports pagination. ```APIDOC ## GET /v1/groups ### Description This endpoint allows you to fetch a list of all groups in your Requestly account. It supports pagination for handling large datasets. ### Method GET ### Endpoint https://api2.requestly.io/v1/groups ### Parameters #### Query Parameters - **offset** (Integer) - Optional - The index from where the results should start. Useful for pagination. Default Value: `0` - **pageSize** (Integer) - Optional - The number of results to return. Maximum value is `75`. Default Value: `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 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 status of the group (e.g., 'Inactive'). - **nextOffset** (Null) - Indicates the next offset for pagination, null if no more results. - **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" }, ... more groups ], "nextOffset": null, "total": 50 } ``` #### Error Responses - **400** - Bad Request. - **401** - Unauthorized action. - **500** - Server error. ``` -------------------------------- ### Generate GUID with Version and Reference Date Source: https://github.com/requestly/requestly-docs/blob/master/general/api-client/environments-and-variables/dynamic-variables.mdx Generates a Globally Unique Identifier (GUID). Supports specifying the version (4 or 7) and an optional reference date for version 7. ```javascript {{$guid 7}} {{$guid 4 "2026-01-01"}} ``` -------------------------------- ### Create a New Git Branch for Contributions Source: https://github.com/requestly/requestly-docs/blob/master/README.md This command sequence is used to start contributing to the Requestly documentation. It forks the repository, checks out the main branch, and then creates a new branch named 'feature/your-contribution' for your specific changes. This is a standard Git workflow for open-source contributions. ```bash git checkout -b feature/your-contribution ``` -------------------------------- ### Get Specific Rule by ID with cURL Source: https://github.com/requestly/requestly-docs/blob/master/public-apis/get-rule.mdx Fetches details for a specific rule using its unique 'ruleId'. The 'ruleId' is a path parameter in the URL. Authentication is handled via the 'x-api-key' header. ```bash curl --request GET \ --url https://api2.requestly.io/v1/rules/Redirect_a9qau \ --header 'accept: application/json' \ --header 'x-api-key: your_api_key' ``` -------------------------------- ### Create Post Mutation (GraphQL) Source: https://github.com/requestly/requestly-docs/blob/master/guides/community-content/using-graphql-in-requestly.mdx This GraphQL mutation example demonstrates how to create a new post with a title and body. It specifies the input parameters and the fields to return upon successful creation. ```graphql mutation CreatePost { createPost( input: { title: "My First Post" body: "Learning GraphQL is easier than I thought!" } ) { id title body } } ``` -------------------------------- ### Import multiple libraries in JavaScript Source: https://github.com/requestly/requestly-docs/blob/master/general/api-client/import-packages-into-your-scripts.mdx Shows how to import multiple external libraries, including 'moment', 'cheerio', and 'uuid', within a single Requestly script. This allows for combined usage of functionalities like date formatting, HTML parsing, and unique ID generation in one script. The example demonstrates loading HTML and extracting text using Cheerio. ```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 GraphQL Request Payload Source: https://github.com/requestly/requestly-docs/blob/master/general/http-rules/advanced-usage/graphql-modify-request-response.mdx This is an example of a typical GraphQL POST request payload. It includes the 'operationName' to specify the desired query and the 'query' field containing the GraphQL query itself. ```bash POST { "operationName": "getUsers", "query": ` query getUsers { users { id email } } ` } ``` -------------------------------- ### Configure Selenium with Requestly Extension (Python) Source: https://github.com/requestly/requestly-docs/blob/master/guides/intercepting-and-modifying-network-requests-in-web-automation-frameworks-like-selenium-and-playwright.mdx Shows how to set up a Selenium WebDriver for Chrome in Python, specifying the path to Chrome for Testing and adding the Requestly CRX extension. This enables automated browser interactions with Requestly rules. ```python from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.binary_location = "/Path/to/chrome-for-testing" # Ensure the path to the CRX file is correct chrome_options.add_extension("/path/to/requestly.crx") driver = webdriver.Chrome(options=chrome_options) print("Selenium driver initialized with Requestly extension.") # driver.get(...) to open pages # driver.quit() ``` -------------------------------- ### Using Variables in API Request Body (JSON Example) Source: https://github.com/requestly/requestly-docs/blob/master/guides/community-content/variables-and-environments-in-requestly.mdx This example demonstrates how to embed variables within a JSON request body. It shows placeholders for `email`, `environment`, and `api_version`, which can be populated with dynamic values. ```json { "email": "{{test_email}}", "environment": "{{environment}}", "api_version": "{{api_version}}" } ``` -------------------------------- ### Using Variables in API Request URLs (Example) Source: https://github.com/requestly/requestly-docs/blob/master/guides/community-content/variables-and-environments-in-requestly.mdx This example shows how to dynamically insert variable values into the URL of an API request. It uses double curly braces `{{variable_name}}` to reference variables like `base_url` and `user_id`. ```plaintext GET {{base_url}}/users/{{user_id}} ``` -------------------------------- ### Write Pre-request and Post-response Scripts in Requestly Source: https://github.com/requestly/requestly-docs/blob/master/general/api-client/quick-start.mdx Provides examples of JavaScript scripts for Requestly. Pre-request scripts can modify the environment before a request is sent, while post-response scripts can process the response data, such as saving a token. ```javascript // Pre-request Script: Add timestamp rq.environment.set("timestamp", new Date().getTime()); // Post-response Script: Save token const response = rq.response.json(); rq.environment.set("auth_token", response.token); ``` -------------------------------- ### Close Extension Welcome Page Source: https://github.com/requestly/requestly-docs/blob/master/guides/intercepting-and-modifying-network-requests-in-web-automation-frameworks-like-selenium-and-playwright.mdx Provides methods to programmatically close the Requestly extension's welcome or post-install tab that might open automatically. This ensures your automation focuses on the intended page. Different approaches are shown for Selenium, Playwright, and Puppeteer. ```javascript // 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); ``` ```javascript const page = await context.newPage(); // Assume the first one is your primary page await page.waitForTimeout(2000); // Get all open pages in the current context const pages = context.pages(); // Iterate through the pages and close any that are not the primary 'page' object for (const openedPage of pages) { if (openedPage !== page) { console.log(`Closing extraneous page: ${openedPage.url()}`); await openedPage.close(); } } // page.goto(...) next ``` ```javascript const pages = await browser.pages(); const page = pages[0]; // Assume the first one is your primary page await page.waitForTimeout(2000); // Close all other pages except the primary one for (const openedPage of pages) { if (openedPage !== page) { console.log(`Closing extraneous page: ${openedPage.url()}`); await openedPage.close(); } } ``` ```javascript import { closeWelcomePage } = require("@requestly/rq-automation"); await closeWelcomePage(driver); ``` -------------------------------- ### Example GraphQL Request Payload without Operation Name Source: https://github.com/requestly/requestly-docs/blob/master/general/http-rules/advanced-usage/graphql-modify-request-response.mdx This example shows a GraphQL POST request where the operation is defined within the 'query' field, and 'operationName' is absent. This scenario requires a different approach for filtering, often using JavaScript. ```bash POST /graphql { "query": ` query getUsers { users { id email } } ` } ``` -------------------------------- ### Example: Validating API Response Structure with rq.expect Source: https://github.com/requestly/requestly-docs/blob/master/general/api-client/rq-api-reference/rq-expect.mdx Provides a practical example of using `rq.expect` within a `rq.test` function to validate the structure of a JSON API response. It asserts that the response is an object, has specific properties ('status', 'data'), and that the 'data' property 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; }); ```