Using Variables inside Postman and Collection Runner
Update: If you want to learn more about variables and Postman, read our 10 Tips for Working with Postman Variables.
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 manually replace values. 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 that lets 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.
- Click on “No environment” in the header.
2. Select “Manage environments” and then on the “Add” button in the modal that comes up.
3. Fill in the values as shown in the screenshot below.
- 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.
Click the duplicate environment icon, and then click on the environment name to edit. Fill in the values, as shown in the screenshot below.
Variables can be used almost everywhere inside Postman. They are available inside:
- URL
- URL params
- Header values
- form-data/url-encoded values
- Raw body content
- 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.
Now select an environment from the environment selection dropdown.
Once an environment is selected, Postman will replace all instances of a variable with its 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”.
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.
On hitting send, we see that the API received the response body with the variable replaced by it’s value.
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 our blog post 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.
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.
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 its 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.
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!
Using variables is essential to maximizing 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 below.
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.
Brian,
Can you email us at help@getpostman.com. We haven’t been able to replicate this issue.
why not convert your csv file to json
http://www.csvjson.com/csv2json
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?
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
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.
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 ?
Is jetpacks open source so I can just fix it myself?
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!
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?
Sorry, i wasnt very clear. {{max_num+1}} in the get/post parameter. Not in the test scripts.
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!
Hi Bob,
Nested JSON structures are not supported. Can you file a feature request at our Github tracker: http://www.github.com/a85/POSTMan-Chrome-Extension/issues
Nice one thanks
Nice tutorial, saves plenty of time for plenty of users.
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…………………………….
Hi, Is there something can make replace servername quickly?
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.
You can use the DevTools window to see the actual payloads that are sent – https://blog.postman.com/2015/06/13/debugging-postman-requests/
There’s no way to show the actual value in the history, though.
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.
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.
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.
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?
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.
How do you escape double curly braces?
Using postman, how the header value taken in php page like $_Request/$_post
When running collection from newman with -d option, how does it know where to look up for the file?
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…
hi,we provide online training & video tutorial for soapui
for free videos refer
http://soapui-tutorial.com/soapui-tutorial/introduction-to-webservices/
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?
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?
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.
Hi, thanks for sharing this great article.
I’m able to setup the the collection runner to use a csv data file but is there anyway to run a individual Post / Get request using a csv file?
This would be useful when testing individual requests before committing them to the collection.
Where has the variable “foo” been defined ? I can only see the definition of variable “test” with value “value_foo”.
How can you assign a variable to a POST body read from a file and not from the environment?
When trying to download the csv example:
Profile cannot be found
This public profile may have been disabled or deleted.