Using variables inside Postman and Collection Runner

Variables are among the most powerful features in Postman. Using variables in your Postman requests, eliminates the need to duplicate requests, which can save a lot of time!

A very common scenario while testing APIs is that the API infrastructure might be present on your local machine, a staging setup, and a production setup. Using variables you can call all these APIs without having to replace values manually. You can also use variables to test for different users (for example, they might need different access tokens), different input values, and a lot more.

With Jetpacks, you get even more power to play with variables. You can extract data from responses and set variable values automatically. You can chain requests one after the other with minimal effort. Variable values are also available inside tests to help you make them more generic.

Data variables let you test multiple instances of a request in one go. Imagine that you want to test an API which let's users post comments on a post. Using data variables you can test for hundreds of variations of a request with different IDs, tokens or content bodies.

Let's look at how you can use variables in your workflow inside Postman.

Create an environment

For this example, let's assume we want to create two environments, production and dev.

  1. Click on "No environment" in the header.

1-dropdown
2. Select "Manage environments" and then on the "Add" button in the modal that comes up.

2-manage-environments
3. Fill in the values as shown in the screenshot below
3-add-environment

  1. Press submit.

To create the dev environment, we can just duplicate this environment so that we don't have to type in variable keys all over again.

4-duplicated-environment

Click the duplicate environment icon, and then click on the environment name to edit. Fill in the values, as shown in the screenshot below.

4-2-duplicate-environment-values

Variables can be used almost everywhere inside Postman. They are available inside:

  1. URL
  2. URL params
  3. Header values
  4. form-data/url-encoded values
  5. Raw body content
  6. Helper fields

To use a variable you need to enclose the variable name with double curly braces – {{my_variable_name}}.

With our environments created, let's try out a sample request. Set the base URL field for the API to {{url}}/post.

6-url-request

Now select an environment from the environment selection dropdown.

5-dropdown-filled

Once an environment is selected, Postman will replace all instances of a variable with it's corresponding value. If no environment is selected, then Postman will try to find a matching global variable.

On hitting send here with the "Production" environment, we see that the request is made to "httpbin.org".

7-sent-request

Change the environment to "dev", and hit send. The request will be made to localhost:5000. It's as easy as that!

Now, let's modify this request by adding a POST body and setting a variable inside the body.

8-post-request

On hitting send, we see that the API received the response body with the variable replaced by it's value.

9-post-request-response

Variables with test scripts

You will need the Jetpacks upgrade for writing test scripts. If you still haven't purchased it, I strongly recommend that you do!

Inside Postman test scripts, you can set environment and global variables using the postman.setEnvironmentVariable and postman.setGlobalVariable functions. You can also access these values using the special environment and globals dictionaries.

Check out this blog entry about how you can extract values from response bodies and assign them to variables. Subsequent calls are made using these values. This is an extremely powerful feature and I am sure you will wonder how you went by without it!

Data variables

Data variables are used inside the Collection Runner. The Collection Runner can run a collection or a folder multiple times. For every iteration, it will pick up new values from a JSON or a CSV file and replace variables in the request with these values.

Let's save our request above in a collection and use data variables to change the response body.

10-data-variables-request

As shown in the screenshot above, I have added a couple of parameters to the JSON body. Values for these will be filled by Postman from a data file.

11-data-variables-test

I have also added a couple of tests which checks whether the correct value was received in the response. You can access the data values for a specific iteration using the special data variable. You can log values to the Chrome DevTools console inside test scripts. Make sure to enable Chrome DevTools first.

Postman lets you import CSV or JSON files as data sources.

The CSV file needs to have the variable names in it's first row. Subsequent rows should be separated by line breaks while the values should be separated by commas. Download a sample CSV file to find out how it looks like.

The JSON file is an array of objects, with each object having key/value pairs. Postman supports only simple numerical and string values inside the JSON file. Download a sample JSON file to find out how it looks like.

12-data-variables-start-test-run

Click on "Choose Files" and import the file that has the data with which the API is to be tested. For this example, we'll just run 2 iterations. I am running this example in the dev environment. Note that environment variables, global variables and data variables can be used together.

After clicking start, the requests are run one after the other. The Collection Runner window tells us that all our tests passed!

13-data-variables-test-run-results

Using variables is essential to maximising your Postman workflow. I hope this tutorial helped you gain a better understanding of this feature. If you have any questions, do let me know in the comments.

  • Brian Conneen

    I'm using collection runner and want the variables in my csv file to be used with my x-www-form-urlencoded post, but the variables don't get populated.

  • Steve McMillen

    I'm trying to build a JetPack that has a file upload in one of the API calls. The upload API uses the binary request body format and I select a local file. The upload API is failing when run in Collection Runner because the filename is not saved with the API.

    For example:
    I save the API with a filename as follows:

    But if I open the API in a new window, the filename is not saved (causing teh request to fail)

    I also tried form-data request body type but same issue occurs.

    Is there any way to save the filename from one session to another?

    • Postman REST Client

      Hi Steve,
      File uploads are an issue. We are trying to figure out what will be the best way to provide this feature. One idea is to have a file repository within Postman and then refer to these within requests as variables. Issue is that storing/loading files inside Postman might slow it down, hence we want to be sure before introducing this feature.

      Abhinav

      • Steve McMillen

        Thanks. I expected this might be the case 🙁

        I think the file repository idea is a good one. For my case I'd really only need 1 or 2 files.

      • Perhaps another possibility would be to allow file references by URI? It would require a fetch first, but at least it would allow collection runners with file upload fields to be used. In this way, too, the file URI could be used in a data file or environment as easily as any other variable.

      • Jiwoks

        It seems you didn't find a solution yet. I'm facing the same problem.
        What about a file reference like we have in the browsers file://paht/to/your/filesystem ?

      • lotan

        Is jetpacks open source so I can just fix it myself?

  • Abdul Nabi

    Hi… one thing I see (though I may be doing it totally wrong) is that if I have a CSV/JSON with multiple sets of env variables to iterate through I need to set the number of iterations to be equal to the length of the elements (or rows in a CSV). Is there a way to set the number of iterations to the number in the set (as we could get those values from a CSV done by a stakeholder)… if not seems that might be handy default behavior (or when loading a file set the iterations to the number)? Or of course I'm just not getting it… Thanks!

  • Nguyen Do Le Bao

    Is there any way to add calculation for environment's variable. Such as {{max_num+1}} ?

    • Like environment.max_num += 1 within the test script?

      • Nguyen Do Le Bao

        Sorry, i wasnt very clear. {{max_num+1}} in the get/post parameter. Not in the test scripts.

  • Bob Steinbeiser

    It seems that nested structures are not supported in a JSON data file? When I try this the Collection Runner seems to hang forever. I'd suggest that if this isn't currently supported, it would make a nice enhancement! If it is supported somehow, please let me know!

  • Balaji Boggaram Ramanarayan

    Nice one thanks

  • Prasanna Venkt

    Nice tutorial, saves plenty of time for plenty of users.

  • abhinay kumar

    i am trying to use my access_token(session id) as variable….. how to do this can you provide me some screen shot for this…………………………….

  • Jared Qin

    Hi, Is there something can make replace servername quickly?

  • xoen

    I used this and it's a very very useful feature.

    The only problem I have with this is that I'm a paranoid: I can't see the final URL of the request before actually making it.

    Even worst, I can't see the actual value in the history after the request is made.

    Maybe I'm missing something and there is a way.

  • Stu Ure

    I must be doing something wrong as I cannot do a GET using a data variable to replace a URL param. Any trick to it? I have a CSV with column name XYZ, and a list of URL's. I have a URL param set as ABC={{XYZ}}. When start the runner it never gets a pass and the response shows the variable name no the value in the CSV.

  • Garret

    When you mention the "global dictionary", I feel like it should say "globals dictionary" because that's actually what the name of the dictionary is. I know it says "globals" in other places of documentation, but I still feel like it should be changed here because it caused some confusion for me while developing some test cases.

  • Ferran Perello

    Hi,

    I'm trying to use an environment variable in a test after a call has been sent and I've read that it is not possible. I need to compare a value of a JSON object with the value that I've stored on an environment variable. Anyone knows if is there a way to solve this issue?

    Here is my test code:

    if (data.folders[0].folder.hasOwnProperty("name") === true){

    tests["Folder found is the correct once"] = data.folders[0].folder.name === {{new_folder_name}};

    } else {

    tests["Folder found isn't the correct once"] = false;

    }

    Thank you in advance,
    Ferran Perello.

  • Vikram

    Hi ,
    We are using postman for MS Azure

    We want to get all users and their all groups in one URL call . Right now we are using

    URL- "https://graph.windows.net/sailpointdev.onMicrosoft.com/users?$expand=memberOf&api-version=1.0"
    to get all users and their group memberships. But output only shows max 20 groups . we wants to get all users and groups.
    Another way is to get all groups by passing objectId of user. but this takes a lot time.
    How to get all users and their all groups in one call and all groups not less than 20??

  • This test section leaves out the part where you do var data = JSON.parse(responseBody);

    At least that was necessary for me testing a different url is that just automatic in the url you are hitting?

  • Nancy

    I have a service request that returns products in random order in the response. So I first need to find the product I want before I can verify the content. Is there a way to loop and use if statements? How would I go about finding the product I want by id, for example? Thanks.

  • shannon carey

    How do you escape double curly braces?

  • gayathryks

    Using postman, how the header value taken in php page like $_Request/$_post

  • Itest

    When running collection from newman with -d option, how does it know where to look up for the file?

  • Ikram Bk

    Im trying to test a POST which includes many POST in service api .ex: add user contains add account .

    Can i do that with Postman?

  • How can I add a variable that is evaluated each time f.ex :

    This can be in any language, it just have to return what I need…

  • Ashish

    hi,we provide online training & video tutorial for soapui

    for free videos refer

    http://soapui-tutorial.com/soapui-tutorial/introduction-to-webservices/

  • Vincent

    How can I save all the response of multiple request? I can see all the result from postman console, but is there any way I can export them to the local?

  • kavya

    We are testing API from postman. After the output is generated for the API, we need to update a column value in the database. Is it possible to do it from postman?

  • Nabzee

    I am trying to post a csv file and get the fields(fields in the csv file) in the response using Postman but I am getting 400 Bad request error.
    Error:
    {
    "status": 400,
    "error": "Bad Request",
    "message": "Required request part 'inFile' is not present",
    "timeStamp": "Tue Feb 07 00:00:17 EST 2017",
    "trace": "org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'inFile' is not present\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestPartMethodArgumentResolver.resolveArgument(RequestPartMethodArgumentResolver.java:192)\n\tat org.springframework.web.method.support.HandlerMethodArgumentResolverComposite….}
    Please let me know how to overcome this issue as I am new to this.