Hey guys! Let's dive into the awesome world of Postman pre-request scripts! These scripts are super handy for setting up your API tests and making sure everything is just right before you hit that send button. We’re going to explore a bunch of examples to help you level up your Postman game. So, grab your coffee, and let's get started!

    What is a Postman Pre-Request Script?

    Pre-request scripts in Postman are snippets of JavaScript code that execute before a request is sent. Think of them as your test’s backstage crew, setting the stage before the main performance. You can use them to:

    • Set environment variables
    • Generate dynamic data
    • Perform authentication
    • Handle conditional logic
    • And much more!

    These scripts live in the “Pre-request Script” tab within your Postman request window. They have access to Postman’s scripting API, letting you manipulate requests, environment variables, and global variables. Essentially, they give you a dynamic way to prepare each request, making your tests more flexible and powerful.

    Why Use Pre-Request Scripts?

    Using pre-request scripts can significantly enhance your API testing workflow. Here’s why you should consider integrating them into your Postman collections:

    • Dynamic Data: Generate timestamps, unique IDs, or random strings to ensure each request is unique and realistic.
    • Authentication: Handle token generation or session management before sending the actual request. This is especially useful for APIs that require complex authentication flows.
    • Conditional Logic: Modify request parameters or headers based on certain conditions. This allows you to create more versatile and adaptable tests.
    • Environment Setup: Set environment variables dynamically based on responses from previous requests or external factors.
    • Debugging: Log information to the Postman console to help diagnose issues and understand the flow of your requests.

    By automating these tasks, you reduce manual effort, minimize errors, and create more robust and maintainable test suites. Pre-request scripts are a powerful tool in any API tester’s arsenal, enabling you to tackle complex scenarios with ease.

    Example 1: Setting an Environment Variable

    One of the most common uses for pre-request scripts is to set environment variables. This allows you to dynamically update values that are used across multiple requests. For instance, you might want to set a timestamp or a unique ID. Here’s how you can do it:

    pm.environment.set("currentTime", new Date().toISOString());
    

    In this example:

    • pm.environment.set(): This is the Postman API function to set an environment variable.
    • "currentTime": This is the name of the environment variable we are creating or updating.
    • new Date().toISOString(): This JavaScript code generates the current timestamp in ISO format.

    Now, you can use {{currentTime}} in your request URL, headers, or body, and it will be replaced with the current timestamp each time the request is executed. This is super useful for testing APIs that require timestamps or for tracking the order of requests.

    For example, if you want to include this timestamp in your request body, you can structure your JSON payload like this:

    {
     "timestamp": "{{currentTime}}",
     "data": "Some data"
    }
    

    Each time you send the request, the {{currentTime}} variable will be replaced with the current timestamp, ensuring that your request is always up-to-date. This technique is invaluable for creating dynamic and repeatable tests.

    Example 2: Generating a Random Number

    Need a random number for your tests? Pre-request scripts can handle that too! Generating random numbers is useful for creating unique identifiers or for simulating real-world data.

    const randomNumber = Math.floor(Math.random() * 1000);
    pm.environment.set("randomNumber", randomNumber);
    

    Here’s what’s happening:

    • Math.random(): This JavaScript function generates a random floating-point number between 0 (inclusive) and 1 (exclusive).
    • * 1000: This multiplies the random number by 1000, giving us a range from 0 to 999.999.
    • Math.floor(): This rounds the number down to the nearest integer, giving us a whole number between 0 and 999.
    • pm.environment.set("randomNumber", randomNumber): This sets the environment variable randomNumber to the generated random number.

    Now, you can use {{randomNumber}} in your requests. This is great for scenarios where you need unique IDs or want to simulate different user inputs.

    For instance, if you are testing an API that creates user accounts, you can use a random number as part of the username to ensure each account is unique:

    {
     "username": "user_{{randomNumber}}",
     "email": "user_{{randomNumber}}@example.com",
     "password": "password123"
    }
    

    This ensures that each time you run the test, a new and unique username is generated, preventing conflicts and making your tests more reliable.

    Example 3: Calculating a Hash

    Sometimes, you need to calculate a hash for authentication or data integrity purposes. Pre-request scripts can handle cryptographic operations using the crypto-js library that's built into Postman.

    const data = "example data";
    const hash = CryptoJS.MD5(data).toString();
    pm.environment.set("dataHash", hash);
    

    Let’s break it down:

    • const data = "example data";: This is the data you want to hash. You can replace this with any string or data you need.
    • CryptoJS.MD5(data): This uses the CryptoJS library to calculate the MD5 hash of the data.
    • .toString(): This converts the hash to a string format.
    • pm.environment.set("dataHash", hash): This sets the environment variable dataHash to the calculated hash.

    Now you can use {{dataHash}} in your requests. This is particularly useful when you need to send hashed data for authentication or verification purposes.

    For example, if your API requires you to send an MD5 hash of a secret key along with your request, you can use this script to generate the hash dynamically:

    {
     "apiKey": "yourAPIKey",
     "hash": "{{dataHash}}"
    }
    

    This ensures that the hash is always calculated correctly and included in your request, enhancing the security and integrity of your API communication.

    Example 4: Setting a Header

    Pre-request scripts are also great for setting headers dynamically. This can be useful for adding authentication tokens, content types, or any other custom headers your API requires.

    pm.request.headers.add({
     key: "X-Custom-Header",
     value: "Custom Value"
    });
    

    Here’s what’s happening in this script:

    • pm.request.headers.add(): This is the Postman API function to add a header to the request.
    • key: "X-Custom-Header": This sets the name of the header to X-Custom-Header.
    • value: "Custom Value": This sets the value of the header to Custom Value. You can replace this with any dynamic value you need.

    You can also use environment variables to set the header value dynamically:

    const authToken = pm.environment.get("authToken");
    pm.request.headers.add({
     key: "Authorization",
     value: `Bearer ${authToken}`
    });
    

    In this case, the Authorization header is set to a bearer token that is stored in the authToken environment variable. This is incredibly useful for handling authentication in your API tests.

    For instance, if your API requires an Authorization header with a bearer token, you can use this script to ensure that the header is always set correctly before the request is sent:

    const token = pm.environment.get("apiToken");
    pm.request.headers.add({
     key: "Authorization",
     value: `Bearer ${token}`
    });
    

    This way, you don’t have to manually update the header for each request, making your tests more efficient and less prone to errors.

    Example 5: Conditional Logic

    Pre-request scripts allow you to implement conditional logic, which means you can modify the request based on certain conditions. This is incredibly powerful for creating flexible and adaptable tests.

    if (pm.environment.get("environment") === "production") {
     pm.environment.set("apiURL", "https://production.example.com/api");
    } else {
     pm.environment.set("apiURL", "https://test.example.com/api");
    }
    

    In this example:

    • pm.environment.get("environment"): This retrieves the value of the environment environment variable.
    • if (pm.environment.get("environment") === "production"): This checks if the environment is set to production.
    • pm.environment.set("apiURL", "https://production.example.com/api"): If the environment is production, this sets the apiURL environment variable to the production API URL.
    • else: If the environment is not production (e.g., test or development),
    • pm.environment.set("apiURL", "https://test.example.com/api"): This sets the apiURL environment variable to the test API URL.

    This script allows you to dynamically switch between different API endpoints based on the environment. You can then use the {{apiURL}} variable in your request URL to ensure that you are always hitting the correct endpoint.

    For instance, if you have different API endpoints for development, testing, and production, you can use this script to dynamically set the API URL based on the current environment:

    if (pm.environment.get("env") === "dev") {
     pm.environment.set("baseURL", "http://localhost:3000");
    } else if (pm.environment.get("env") === "staging") {
     pm.environment.set("baseURL", "https://staging.example.com");
    } else {
     pm.environment.set("baseURL", "https://production.example.com");
    }
    

    This ensures that your tests are always running against the correct environment, making your testing process more reliable and efficient.

    Conclusion

    Postman pre-request scripts are a game-changer for API testing. They allow you to dynamically set up your requests, handle authentication, generate data, and implement conditional logic. By using these scripts, you can create more robust, flexible, and maintainable test suites. So go ahead, experiment with these examples, and take your Postman skills to the next level! Happy testing, guys!