Featured image of post Postman Advanced Guide

Postman Advanced Guide

Advanced usage of Postman

Introduction

In the previous article “Mastering Postman: Basic Guide”, we introduced the main features and basic usage of the Postman tool. As the most widely used API testing tool currently, besides providing a user-friendly UI interface and basic functions such as authentication, header, body settings, request submission and response parsing for HTTP protocol, Postman also provides very rich testing assistance capabilities. In this article, we will introduce Postman’s advanced scripting features in detail.

Postman Variables

In API testing tools, variables are of great significance for the reuse and flexible matching of API messages. As a professional API testing tool, support for variables is essential.

Postman provides rich variable support, defining 5 different types of variables with different scopes, making the use and management of variables more flexible and targeted. The following figure shows the official scope of different types of variables:

image

From outside to inside, the scope gradually becomes smaller, and at the same time, the priority becomes higher. That is, when there are variables with the same name, the variables of the inner layer type will take precedence. Let’s explain these variable types in detail with examples:

Global Variables

Global variables have the largest scope among all variable types. Once set, global variables can take effect in all places where variables can be used in the Postman tool.

Let’s look at how to set global variables in Postman: Open the environment management interface in the upper right corner of the tool: image

Select global variable management: image

Add Global variable: image

In this example, we set a global variable name with a value of 1. In Postman, variables are represented using double curly braces, like {{ variable }}. Taking the Github API as an example, let’s get the user information where the username is the value of the variable name.

https://api.github.com/users/{{name}}

After entering double curly braces in the URL, it will automatically suggest the variable types we need.

image

After sending the request, check the Postman response area, and you can see that we got the user information for username 1.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
{
    "login": "1",
    "id": 1825798,
    "node_id": "MDQ6VXNlcjE4MjU3OTg=",
    "avatar_url": "https://avatars2.githubusercontent.com/u/1825798?v=4",
    "gravatar_id": "",
    "url": "https://api.github.com/users/1",
    "html_url": "https://github.com/1",
    "followers_url": "https://api.github.com/users/1/followers",
    "following_url": "https://api.github.com/users/1/following{/other_user}",
    "gists_url": "https://api.github.com/users/1/gists{/gist_id}",
    "starred_url": "https://api.github.com/users/1/starred{/owner}{/repo}",
    "subscriptions_url": "https://api.github.com/users/1/subscriptions",
    "organizations_url": "https://api.github.com/users/1/orgs",
    "repos_url": "https://api.github.com/users/1/repos",
    "events_url": "https://api.github.com/users/1/events{/privacy}",
    "received_events_url": "https://api.github.com/users/1/received_events",
    "type": "User",
    "site_admin": false,
    "name": "Michael",
    "company": null,
    "blog": "",
    "location": "San Francisco, CA",
    "email": "mbalaban1989@gmail.com",
    "hireable": null,
    "bio": null,
    "public_repos": 3,
    "public_gists": 0,
    "followers": 15,
    "following": 0,
    "created_at": "2012-06-07T06:10:07Z",
    "updated_at": "2019-01-17T08:29:21Z"
}

Collection and Collection Variables

Let’s look at another variable type: Collection variables. First, let’s understand the concept of Collection. Collection is a grouping unit for organizing APIs in Postman, and Postman mainly uses Collection as a basic unit for configuration storage. We can think of Collection as the concept of a test suite in software testing.

Collection variables are variables with a scope on the Collection. These variables will only take effect on the Collection where the variable is set. Setting method: Select Edit Collection image

Add Collection variables in the variable page. In this example, we add a variable also named “name” to the Github Collection image

Save the user retrieval API from the previous example to the Github Collection (we can create a sub-directory under the Collection, note that directories do not support setting directory-level variables, Collection variables will still take effect for APIs in sub-directories), and let’s submit this API again image

At this point, we can see that the Collection variable we set has taken effect, and we get the user information for name 2. Note that we still have a global variable name with a value of 1, and we can see that Collection variables have a higher priority than global variables.

Environment and Environment Variables

Environment is a very useful concept in Postman. Those who have done software testing understand that we encounter different software environments in our actual work, corresponding to different operating scenarios of our system under test. For example, a typical internet company may have the following different environments during development:

  • Development environment
  • Integration environment (joint debugging environment)
  • System testing environment
  • Pre-production environment
  • Production environment
  • Performance testing environment
  • Security testing environment

Different environments often have significant differences in access methods, network topology, access permissions, and hardware configurations. Postman introduces the concept of Environment and manages a set of environment configurations through Environment variables, making it convenient for us to switch between different environments.

In the environment management interface, you can add environments and related variables for that environment. In this example, we add a GitChat environment and set an environment variable name = 3. image After setting up the environment, on the user retrieval API interface, select the corresponding GitChat environment, and submit the request again. We can see that the environment variable has taken effect, retrieving user information for name 3, and similarly, we can see that the environment variable has a higher priority than the Collection variable. image

Local Variables

Local variables are variables with the smallest scope, which only take effect in the current request. Local variables can be set in the pre-request script or test script of the request. Let’s look at an example:

In the pre-request script of the user retrieval API, we add the following code:

1
pm.variables.set("name", "4");

This sets a local variable name = 4. After submitting the request, we can see that the local variable has taken effect, retrieving user information for name 4, and we can see that the local variable has the highest priority among all variable types.

Data Variables

Data variables are a special type of variable in Postman. They are not set directly like other variables but are used in conjunction with data files. This is very useful when we need to test the same API with different data.

Let’s look at how to use data variables: First, prepare a data file, which can be in CSV or JSON format. Here we use a CSV file as an example:

1
2
3
4
name,age
5,20
6,21
7,22

Then in Postman, select Runner: image

Select the Collection and API to run, and import the data file: image

After clicking Run, Postman will automatically read the data from the data file and execute the API multiple times. Each time it will use a different row of data from the data file, and we can use these data through variables like {{name}} and {{age}}.

Dynamic Variables

In addition to the five types of variables mentioned above, Postman also provides some built-in dynamic variables that can be used directly without setting. These variables are mainly used to generate some random data or get the current time and other information. Here are some commonly used dynamic variables:

  • {{$guid}}: Generate a GUID
  • {{$timestamp}}: Get the current timestamp (in seconds)
  • {{$randomInt}}: Generate a random integer
  • {{$randomEmail}}: Generate a random email address
  • {{$randomUserName}}: Generate a random username
  • {{$randomAlphaNumeric}}: Generate a random alphanumeric string
  • {{$randomColor}}: Generate a random color name
  • {{$randomHexColor}}: Generate a random hexadecimal color code

For example, if we want to test an API that creates a user, we can use these dynamic variables to generate test data:

1
2
3
4
5
6
7
POST https://api.example.com/users
{
    "id": "{{$guid}}",
    "username": "{{$randomUserName}}",
    "email": "{{$randomEmail}}",
    "created_at": {{$timestamp}}
}

Variable Scope and Priority

After understanding these different types of variables, let’s summarize their scope and priority:

  1. Scope:

    • Global variables: Effective throughout Postman
    • Collection variables: Effective within the Collection
    • Environment variables: Effective within the selected environment
    • Local variables: Only effective in the current request
    • Data variables: Effective during Collection Runner execution
  2. Priority (from highest to lowest):

    • Local variables
    • Data variables
    • Environment variables
    • Collection variables
    • Global variables

When variables with the same name exist in different scopes, the one with higher priority will take effect.

Postman Scripts

Postman provides powerful scripting capabilities, allowing us to perform various operations before and after requests. Postman scripts are written in JavaScript and can be used to set variables, perform tests, process response data, and more.

Pre-request Scripts

Pre-request scripts are executed before a request is sent. They can be used to set variables, perform authentication, or prepare data for the request. Let’s look at some examples:

  1. Setting variables:
1
2
3
4
5
6
7
8
// Set a local variable
pm.variables.set("name", "postman");

// Set an environment variable
pm.environment.set("token", "abc123");

// Set a global variable
pm.globals.set("api_key", "xyz789");
  1. Generating random data:
1
2
3
// Generate a random user ID
const userId = Math.floor(Math.random() * 1000);
pm.variables.set("userId", userId);
  1. Performing authentication:
1
2
3
4
5
6
7
8
// Generate a timestamp for authentication
const timestamp = Math.floor(Date.now() / 1000);
pm.variables.set("timestamp", timestamp);

// Generate a signature
const data = pm.variables.get("api_key") + timestamp;
const signature = CryptoJS.MD5(data).toString();
pm.variables.set("signature", signature);

Test Scripts

Test scripts are executed after a response is received. They can be used to verify the response, extract data from the response, or set variables for subsequent requests. Let’s look at some examples:

  1. Verifying response status:
1
2
3
4
// Check if the response status is 200 OK
pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});
  1. Verifying response body:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Check if the response contains specific text
pm.test("Response contains user data", function () {
    pm.expect(pm.response.text()).to.include("username");
});

// Check if a specific field has the expected value
const responseData = pm.response.json();
pm.test("User ID is correct", function () {
    pm.expect(responseData.id).to.equal(123);
});
  1. Extracting data from the response:
1
2
3
// Extract the token from the response and save it as an environment variable
const responseData = pm.response.json();
pm.environment.set("token", responseData.token);
  1. Performing complex validations:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Check if the response time is less than 200ms
pm.test("Response time is less than 200ms", function () {
    pm.expect(pm.response.responseTime).to.be.below(200);
});

// Check if the response headers contain specific values
pm.test("Content-Type header is present", function () {
    pm.response.to.have.header("Content-Type");
});

// Check if the response body is valid JSON
pm.test("Response is valid JSON", function () {
    pm.response.to.be.json;
});

Postman Console

Postman provides a console that can be used to view logs and debug scripts. You can open the console by clicking on the “Console” button in the bottom left corner of the Postman window, or by pressing the Alt+Ctrl+C (Windows/Linux) or Option+Command+C (Mac) keyboard shortcut.

In your scripts, you can use console.log() to output information to the console:

1
2
console.log("This is a debug message");
console.log("Variable value:", pm.variables.get("name"));

This is very useful for debugging your scripts and understanding what’s happening during execution.

Postman Collection Runner

The Collection Runner is a powerful feature in Postman that allows you to run a collection of requests in a specific order. This is particularly useful for testing API workflows or running the same request with different data.

To use the Collection Runner:

  1. Click on the “Runner” button in the top left corner of the Postman window
  2. Select the collection or folder you want to run
  3. Configure the run settings (iterations, delay, data file, etc.)
  4. Click on the “Run” button

The Collection Runner will execute the requests in the specified order and display the results, including any test results.

Postman Newman

Newman is the command-line companion for Postman. It allows you to run and test a Postman collection directly from the command line. This is particularly useful for integrating Postman tests into your CI/CD pipeline.

To use Newman, you first need to install it via npm:

1
npm install -g newman

Then you can run a collection using:

1
newman run collection.json -e environment.json

Where collection.json is your exported Postman collection and environment.json is your exported Postman environment.

Newman also supports various options for customizing the run and generating reports:

1
newman run collection.json -e environment.json --reporters cli,html --reporter-html-export report.html

This command will run the collection and generate both CLI and HTML reports, with the HTML report saved to report.html.

Conclusion

In this article, we’ve explored the advanced features of Postman, including variables, scripts, the console, Collection Runner, and Newman. These features make Postman a powerful tool for API testing and development.

By mastering these features, you can:

  • Create more flexible and reusable API tests
  • Automate complex testing scenarios
  • Validate API responses with detailed assertions
  • Generate comprehensive test reports
  • Integrate API testing into your CI/CD pipeline

In the next article, we’ll dive deeper into Postman’s automation capabilities and explore how to use Postman for API monitoring and documentation.

Built with Hugo
Theme Stack designed by Jimmy