Sometimes, the response from a request is required first in order to continue with all the other API requests currently stored in your Postman folders. Think of a request that, in order to return results, it requires from you to be authenticated, so a typical workflow would be:
- authenticate yourself with a proper username and password;
- get an authentication token;
- update your other requests to use this new token.
To avoid updating manually all your request headers with the new `auth token`, you can use environments and variables in Postman.
Setting up Environments and Variables
Environments is a set of key-value pairs that allows you to customize requests using variables. Variables can be used in the following form – {{variableName}}
and, whenever the {{variableName}} appears, it will be replaced by its corresponding value.
For example, in the screenshot above we have created a “Dev locally” environment where the variable WebAppUrl will be replaced by localhost:4000
whenever found, and when the AuthToken variable is found by N/A.
So, if you need to be authorized to access some resources, firstly you need to call `localhost:4000/oauth/token` to get an authentication token and then use this token to your other request, let’s say `localhost:4000/api/categories`.
To avoid copying and pasting the access_token
returned from the first request to update the variable AuthToken
to be used in the second request, you can use test scripts to make your life easier.
Test Scripts
The test script runs inside a sandbox and Postman provides the postman object to interact with the main Postman context. In addition, you can extract data from responses and chain requests using test scripts.
In our case, click on Tests tab and parse the response body from auth request:
var data = JSON.parse(responseBody);
then, you can update the environment variable AuthToken through the following command:
postman.setEnvironmentVariable("AuthToken", data.access_token);
Now all other calls will use the new updated AuthToken without the need to manually update the environment variable.
How do you select 001-0000084765 from below JSon response.
Tried this code but doesn’t work
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable(“HierarchyId”,jsondata.HierarchyId);
To access `hierarchyId` you can do the following:
One thing that might help you is Postman console. You can open it from `View -> Show Postman Console` and then you use `console.log` to help you. More info here
Thank you , It worked for Me .
Thank you.. it worked
how to parse an xml response:
10:00:c4:f5:7c:52:2a:18
I tried this and it did not like the last response.fibrechannel-switch.name:
var jsonData = xml2Json(responseBody);
var response = JSON.parse(jsonData);
postman.setEnvironmentVariable(“switchName”, response.fibrechannel-switch.name);
thanks.
To view the output of your `jsonData` variable you can use Postman Console. Open it from `View -> Show Postman Console` and then you use `console.log` to help you.
Usually the parsing is a little different than you might expect, but with Console you ‘ll figure out the problem easily.
I Am bound to get XML response only :
I want to take “credentials token” and “site id” as my env ver, how could I be able to achieve the same !! please help
response:
Firstly, you can convert XML to JSON with `var json = xml2Json(responseBody);` and then get the variables that you want from `json` object.
Worked like a charm. Thanks!
Awesome. That is something that i am looking for.
How to get “Qk4oSI” from the response:
You could do that through `data.promocode`.
How would I get BackCustomerID? I’ve tried:
You response is an array, so you need to get the first element:
That worked great – thank you for the quick reply.
How to set the environment variable only if json object exits and not empty?
You can include those conditions in your `Tests` script.
{
“serial”: “123456”,
“headers”: {
“Authorization”: “Signature keys=\”/smarId/hello/1234.123445\”,signature=\”www.hello.com/””
}
I want only */smarId/hello/1234.123445* as environment variable
If only the Signature keys change, then you can do the following:
You can learn more about string interpolation and template literals in this link
How to extract the ETag value from response header and use it dynamically across other requests?
Let’s assume you have this request from OpenWeather API:
To access the ETag value you can use the following code in Tests panel:
For more info on postman’s response API you can have a look here
Hi I am new to postman, can we write JSON object in pre-req?
and use this in the body?
In order to that one way would be to do the following:
Step 1: Stringify your object and assign it to an environment variable in `Pre-request Script` tab:
Step 2: In Body use that variable in your object:
Note the `{{}}` which are used in order to use this variable.
Hi, I was trying to add a test for a 1 call to add auth token,
Requirement : If 401 error is thrown then add header with Authorization by calling the auth and copying that token and automatically adding it in the call which I am using. Please help me out, I am not able to do this scenario.
It’s taking the token as null
Code :
Can you please use the Postman Console to see the actual json response in case it’s wrapped in another object? From top level menu, choose View -> Show Postman Console (CMD/CTRL + ALT + C) and `console.log(response.json())` before `pm.globals.set(“jwttoken”, response.json().token);`.
Once you have console opened, please add `console.log(‘1/2/3’, pm.globals.toObject())` to check if global values change properly and use the number to understand the order everything is executed.
The last thing I would try is before setting the new value, firstly unset and then set the variable again:
Your code looks fine, so I bet you might have missed something while accessing or setting global values properly.
Token has been captured but when it’s trying to add it to the new request call, the token is passing has undefined. I have set the jwttoken variable as Global and in the headers have intialized variable as :
key : Authorization : Bearer {{jwttoken}}
and in console for undefined :
jwttoken: undefined
When I unset and set also same error is seen.
Can you please check that you don’t have an environment variable with the same name `jwttoken` as environment variable?
There might be an issue with the variable scoping (https://learning.postman.com/docs/postman/variables-and-environments/variables/#variable-scopes).
Can you try environment variables instead of globals. So instead of using `pm.globals` to use `pm.environment`.
Hey!! I don’t have any same variable at environment level and it didn’t work when changed it to environment , the access token is getting added if I am adding the test at collection level by parsing the data.
But for the api level, in the last step jwttoken is going as undefined
Hey Thanks NVM , worked, so changed the data response.json().token to response.json().jwttoken
Great, so the problem was on the property of the response object. Hope I helped. Have a great day 🙂
Hey,
Last time your idea worked for me thanks for that, I could not find option to reply, so conveying it here.
And this time I have a doubt with setting up random values to environement level and use it.
Actually I wanted to add a random value in place of name and namekey and set it in environment level. So I have attached the code. But it’s going as undefined error always. I am not if I can do this with the below code. So my body is always dynamic so I want to generate random values, whenver it runs and set it and use it for other API. Thanks in advance, my api structure :
If you want to create an object with all the properties being random on each request you can create an object in `Pre-Request script`, set it in an environment variable and then use that environment variable in `Request body`, as shown in the screenshot below:
Hi Can you please let me know how can i store DeviceID value from the given below response:
{
“connectionString”: “HostName=devicenet;DeviceId=71014;SharedAccessKey=fbwsdxs +++++=”,
“username”: “abc@dev.onmic.com”,
“password”: “abcdf123”
}
If you just want the `DeviceId` from your response, you can create a test and use the following quick & dirty way:
One advice though, you should avoid sending sensitive data in your API responses, not a very good practice.
Hope I helped 🙂
Hi, I am capturing the few fields from the API response in the Tests Tab using “pm.globals.set(“actualUsername”, jsonData.identifier.identifier);”
How can I get the value of key: ‘actualUsername’ in other tests of API?
If your value is already set in global variables you can access it through `pm.globals.get(“actualUsername”)` and use it throughout all your other tests. As your value is previously stored in Global variables, it will be available in your workspace for all your APIs.
You can learn more here
Help me to Write a Script for the “transactionId” the same needs to pass in PUT Method URL as variable ? as this transactionID is dynamic.
It Creates New ID transaction ID whenver user Initiate theAPI Request
Please help.
Below is the code i used
In order to access `transactionId` that is nested under `data` object, instead of `pm.environment.set(“transactionId”, response.transactionId);` you should use `pm.environment.set(“transactionId”, response.data.transactionId);`
How do you select the value of EntityToken from the JSON response below?
You could parse your response and then you access the nested property `EntityToken` as you would do in any json object: