Skip to content

How To Use Variable In Body Postman

API Testing Blog

Leveraging Variables in Postman’s Request Body for Efficient API Testing

Postman’s powerful variable system allows you to create dynamic and reusable API requests. This guide dives into the techniques for incorporating variables directly into your request body, streamlining your testing process and enhancing flexibility.

1. Understanding Variables and Their Uses

Variables in Postman are like placeholders that can store data, which can be dynamically updated throughout your testing workflow. In the context of request bodies, they offer:

  • Parameterized Requests: Define reusable request structures that can be easily adapted to different test scenarios, eliminating repetitive manual modifications.
  • Data-Driven Testing: Easily test your API with various inputs by defining a set of variables representing different data points.
  • Environment-Specific Values: Store sensitive information like API keys or URLs in environment variables, making your tests more secure and adaptable to different environments.

2. Declaring Variables in Postman

Before injecting variables into your request body, they need to be declared. Postman provides several ways to define variables:

  • Global Variables: Accessible across all your collections and environments. These are useful for constants or frequently used values.
  • Collection Variables: Scope limited to a specific collection, allowing you to manage variables relevant to a particular set of requests.
  • Environment Variables: Scope limited to a specific environment. Useful for storing environment-specific configurations.
  • Data Files: Import external data files (like CSV or JSON) to define variables based on their content. This is ideal for data-driven testing.

2.1. Defining Variables in the Postman Interface

  1. Go to Postman’s workspace and navigate to the “Variables” tab.
  2. Select the desired scope (Global, Collection, or Environment).
  3. Click the “Add a variable” button.
  4. Enter a variable name and its corresponding value.

2.2. Utilizing Data Files for Variables

  1. Click the “Variables” tab and choose the “Add a variable” option.
  2. Select the “Data” option.
  3. Choose your data file (CSV, JSON, etc.).
  4. Choose your data source, “File.”
  5. Provide the path to your data file.

3. Injecting Variables into the Request Body

3.1. Using Dynamic Variables in the Body Tab

  1. Select your request in Postman.
  2. Navigate to the “Body” tab and choose the appropriate content type (JSON, XML, Text, etc.).
  3. Within the body field, simply enclose variable names within double curly braces {{variableName}}.

Example:

{
"name": "{{userName}}",
"email": "{{userEmail}}",
"age": {{userAge}}
}

3.2. Dynamic Values with the “Pre-request Script”

For more complex scenarios where you need to manipulate variable values before sending your request, you can leverage Postman’s pre-request script:

  1. Go to the “Pre-request Script” tab of your request.
  2. Use JavaScript to assign values to variables before the request is sent.

Example:

// Generate a random number
const randomNumber = Math.floor(Math.random() * 100);
// Set a variable called "randomValue"
pm.variables.set("randomValue", randomNumber);

4. Practical Examples of Using Variables in the Body

4.1. Data-Driven Testing with JSON Variables

Imagine you’re testing a user creation API. You want to send a request multiple times with different user data. You can store the user information in a JSON data file:

Data File (users.json):

[
{
"name": "John Doe",
"email": "john.doe@example.com"
},
{
"name": "Jane Smith",
"email": "jane.smith@example.com"
}
]

Postman Request Body:

{
"name": "{{name}}",
"email": "{{email}}"
}

Step-by-Step:

  1. Create a ‘users.json’ file with your data.
  2. Go to the “Variables” tab and define a data file variable named “users.”
  3. Choose the “users.json” file as your data source.
  4. In your request body, replace “name” and “email” fields with {{name}} and {{email}}.
  5. Run the request, and Postman will iterate through each user object in your JSON file, sending a request with each set of data.

4.2. Using Environment Variables for API Key Management

Let’s say you have a “Production” and “Staging” environment for your API. Each environment might have a different API key.

Step-by-Step:

  1. Create two environments, “Production” and “Staging.”
  2. In each environment, define an environment variable named “apiKey” with the corresponding API key for that environment.
  3. In your request body (assuming it requires an API key) use the {{apiKey}} variable.
  4. Select your desired environment before running the request.

Your request will automatically use the correct API key based on the selected environment.

5. Advanced Variable Use: Collections and Iterations

Postman allows you to organize your requests into collections. Variables defined within a collection can be shared among requests in that collection, increasing code reusability. You can also use variable iteration to loop through lists of data within a collection, automating repetitive tests.

Example (Collection):

  1. Inside a collection, define a variable (e.g. userList) with a list of users:
[
{ "name": "John Doe", "email": "john.doe@example.com" },
{ "name": "Alice Jones", "email": "alice.jones@example.com" }
// ... more users
]
  1. Create a request within this collection that iterates through the userList variable, sending a POST request for each user:
pm.test("Looping through user list", function () {
pm.collectionVariables.get('userList').forEach(user => {
pm.environment.set("currentUserName", user.name);
pm.environment.set("currentUserEmail", user.email);
pm.sendRequest({
url: "https://myapi.com/users",
method: "POST",
body: {
"name": "{{currentUserName}}",
"email": "{{currentUserEmail}}"
}
});
});
});

In this example, the script iterates through each user in the userList collection variable, setting the currentUserName and currentUserEmail variables for each iteration.

6. Benefits of Variable Usage

By incorporating variables into your request bodies within Postman, you reap numerous advantages:

  • Reusability: Save time and effort by creating reusable request templates that can be easily modified to test different scenarios.
  • Flexibility: Adapt your tests quickly to different data inputs, environments, and API endpoints without extensive manual changes.
  • Efficiency: Reduce repetitive tasks and streamline the testing process, making your workflow more efficient.
  • Data-Driven Testing: Perform robust testing with various input combinations, ensuring thorough API coverage.
  • Reduced Maintenance: Minimize changes required to maintain your tests as your API evolves.

Variables in Postman’s request bodies are potent tools for API testing. Utilize them to build robust, flexible, and efficient tests, and watch your API testing efficiency soar.

API Testing Blog