Skip to content

How To Use Postman Cli

API Testing Blog

Unleashing the Power of Postman CLI for API Testing

Postman CLI is a powerful command-line interface (CLI) tool that allows you to interact with your APIs directly from your terminal. It provides a flexible and efficient way to automate API testing, manage collections, and even generate API documentation. This guide will take you through the essential aspects of using Postman CLI for your API testing needs.

Installation and Setup

Before embarking on your API testing journey with Postman CLI, you need to install it.

  1. Install Node.js: Postman CLI is built on Node.js, so you’ll need it installed. Download the appropriate installer from https://nodejs.org/ and follow the installation instructions for your operating system.

  2. Install Postman CLI: Once Node.js is installed, you can install Postman CLI using npm (Node Package Manager) - which is usually included with Node.js. Open your terminal and run:

    Terminal window
    npm install -g newman

    This command installs newman, the core command-line tool for Postman.

Getting Started with Basic Requests:

Let’s jump into making basic API requests with Postman CLI. We’ll use the newman run command to execute a collection of API requests.

1. Create a Postman Collection:

  • In Postman (GUI): Start by creating a collection in Postman’s graphical interface. You can add requests to this collection.
  • Alternatively: You can define a collection directly in JSON format, which you can later use with the CLI.

2. Generate a Collection File:

  • Using the Postman GUI:

    • Open your collection in Postman.
    • Click the “Export” button (looks like a 3-dot menu) and choose “Collection (v2.1).” Save the file, which will be a .json file containing your collection data.
  • Creating a JSON File Manually: Let’s create a simple collection with a GET request to the https://reqres.in/api/users endpoint:

    {
    "info": {
    "_postman_id": "856175d2-b798-4861-aea4-0fa24f73918a",
    "name": "Example Collection",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
    },
    "item": [
    {
    "name": "Get Users",
    "request": {
    "method": "GET",
    "header": [],
    "url": {
    "raw": "https://reqres.in/api/users",
    "protocol": "https",
    "host": ["reqres", "in"],
    "path": ["api", "users"]
    }
    },
    "response": []
    }
    ]
    }

    Save this JSON file as collection.json.

3. Running a Collection with newman run:

  • Directly from a file: Use the command to execute the collection.json file we just created:

    Terminal window
    newman run collection.json
  • Using a URL: You can also directly run a collection by specifying its URL:

    Terminal window
    newman run https://www.getpostman.com/collections/YOUR_COLLECTION_ID

    Replace YOUR_COLLECTION_ID with the actual Postman collection ID.

4. Viewing the Results:

  • By default, Postman CLI will print the test results to your terminal.

  • You can also specify a report format using the -r flag:

    Terminal window
    newman run collection.json -r cli,junit

    This will generate a CLI report and a JUnit report in newman_report.xml. You can also use html, json or markdown as report formats.

Adding Assertions and Tests

Testing goes beyond simply making a request. You need to validate the response data to ensure your API is behaving as expected.

1. Assertions:

  • In Postman (GUI): Add “Tests” to your requests in Postman, and use the Postman Test script language.
  • In JSON (manual): In your collection.json, add event and script as follows:
{
"item": [
{
"name": "Get Users",
"request": {
// ... request details ...
},
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test(\"Status code is 200\", function () {",
" pm.expect(pm.response.code).to.be.eql(200);",
"});",
"pm.test(\"Response has data\", function () {",
" pm.expect(pm.response.json().data).to.be.an('array');",
"});"
],
"type": "text/javascript"
}
}
]
}
]
}
This snippet adds two test assertions: one checks the status code, and another checks that the response has a `data` field which is an array.

2. Running Tests with newman run:

  • Execute the newman run command as before, and the results of your tests will be displayed:

    Terminal window
    newman run collection.json

Environment Variables and Data Files

Using environment variables and data files enhances your API tests by providing a way to manage different configurations and data sources.

1. Environment Variables:

  • In Postman (GUI): Define environment variables in the Postman environment manager.

  • In JSON (manual): Add an environment section to your collection.json:

    {
    "environment": {
    "id": "2124509f-b0ab-409e-85d7-61f159e09466",
    "name": "Example Env",
    "values":
    [
    {
    "key": "API_BASE_URL",
    "value": "https://reqres.in/api",
    "enabled": true
    }
    ]
    }
    }
  • Using Environment Variables in Tests: Access them using pm.environment.get('API_BASE_URL').

2. Data Files:

  • In Postman (GUI): Create data files with different sets of data.

  • In JSON (manual): Use the iterationData field in your collection.json:

    {
    "item": [
    {
    "name": "Create User",
    "request": {
    "method": "POST",
    "header": [],
    "url": "{{API_BASE_URL}}/users",
    "body": {
    "mode": "raw",
    "raw": "{\n \"name\": \"{{user_name}}\",\n \"job\": \"{{job}}\"\n}"
    }
    },
    "iterationData": [
    {
    "user_name": "John Doe",
    "job": "Software Engineer"
    },
    {
    "user_name": "Jane Smith",
    "job": "Data Scientist"
    }
    ]
    }
    ]
    }
    • Using Data in Tests: Use pm.iterationData.get('user_name') to access data values.

3. Running with Environments and Data:

```bash
newman run collection.json -e environment.json -d data.json
```
* `-e environment.json`: Loads an environment file.
* `-d data.json`: Loads a data file for data-driven testing.

Integrating with CI/CD

Postman CLI seamlessly integrates with your CI/CD pipelines, allowing you to automate your API testing as part of your build and deployment process.

1. Triggering Tests from CI/CD:

  • Jenkins: Use the newman command within your Jenkinsfile.
  • GitHub Actions: Include the newman command in your YAML workflow file.
  • Azure DevOps: Utilize the newman command in your pipeline definition.

2. Example Jenkinsfile:

```groovy
pipeline {
agent any
stages {
stage('API Tests') {
steps {
sh 'newman run collection.json -e environment.json'
}
}
}
}
```

Advanced CLI Features

Take your API testing prowess to the next level with these additional features:

  • Command Line Options: The newman command supports numerous command-line options for controlling test execution, reporting, and more. Refer to the official Postman CLI documentation for a complete overview: https://learning.postman.com/docs/newman/command-line/

  • Custom Scripts: You can write custom JavaScript scripts to perform complex actions during tests. Explore the Postman Test script language for more advanced features.

  • API Documentation Generation: Generate API documentation, such as OpenAPI (Swagger) specifications, using newman and appropriate options.

  • Plugins: Postman provides plugins for newman, expanding its capabilities. For example, the newman-reporter-html plugin generates interactive HTML reports for your tests.

Conclusion

Postman CLI provides a versatile and powerful command-line tool to streamline your API testing workflow. From basic requests to advanced tests and integrations with CI/CD, Postman CLI empowers you to build robust and automated API testing strategies, ensuring the quality and reliability of your APIs.

API Testing Blog