How to update environment variables based on a response in Postman

Written by ppolyzos

Software engineer based in beautiful Luxembourg


  1. chenna

    How do you select 001-0000084765 from below JSon response.

        "PageOfResults": [
                "RoleId": 8,
                "Account": {
                    "HierarchyId": "001-0000084765",
                    "AccountId": "NT9041360",
                    "Name": {
                        "Full": "Mr Philip ppppppppppppppp Lee",
                        "Medium": null,
                        "Short": null,
                        "Preferred": null
                    "Type": "Individual",
                    "Status": "Active",
                    "DateCreated": "2016-08-29",
                    "ExternalAccountId": null,
                    "Links": null
                "Customer": {
                    "CustomerId": 14293,
                    "Status": "Active",
                    "PersonalDetails": {
                        "Name": {
                            "Title": "Mr",
                            "Given": "Philip",
                            "Middle": "ppppppppppppppp",
                            "Family": "Lee",
                            "Suffix": null,
                            "Salutation": null
                        "MaritalStatus": "NotSpecified",
                        "Gender": "Male",
                        "GovernmentIdentifiers": [
                                "Value": "",
                                "Type": "TaxFileNumber",
                                "Country": "AUS"
                        "DateOfBirth": "1980-03-01",
                        "Nationality": "NotSpecified",
                        "CountryOfResidency": "NotSpecified",
                        "TownOfBirth": null,
                        "Countries": [
                                "Type": "TaxCountryOfResidence",
                                "Country": "AUS",
                                "TaxNumber": ""
                        "Links": null
                    "ExternalCustomerId": null,
                    "HierarchyId": "015-0000014293",
                    "UserId": 114591,
                    "Links": null
                "Role": "Individual",
                "Links": null
        "TotalNumberOfResults": 1,
        "Links": null

    Tried this code but doesn’t work

    var jsonData = JSON.parse(responseBody);

    1. ppolyzos

      To access `hierarchyId` you can do the following:

      var hierarchyId = jsonData.PageOfResults[0].Account.HierarchyId

      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

  2. Jhuang

    how to parse an xml response:


    I tried this and it did not like the last
    var jsonData = xml2Json(responseBody);
    var response = JSON.parse(jsonData);


    1. ppolyzos

      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.

      1. Subhajit

        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


  3. niti

    How to get “Qk4oSI” from the response:

      "id": 82,
      "flagForAmountType": true,
      "promocode": "Qk4oSI",
      "promocodeUsedType": "investment_cost",
      "amount": 1000.000,
      "amountUsed": 0,
      "createDate": "2019-08-09",
  4. Cain

    How would I get BackCustomerID? I’ve tried:

    var data = JSON.parse(responseBody);
    postman.setEnvironmentVariable("BackCustomerID", data.BackCustomerID);
            "CustomerID": 0,
            "BackCustomerID": "P0456",
            "BackCustomerName": "Account_P0456",
    1. ppolyzos

      You can include those conditions in your `Tests` script.

      const data = JSON.parse(responseBody);
      if (data && data.obj1 && data.obj1.prop1) {
         postman.setEnvironmentVariable('YOUR_VARIABLE', data.obj1.prop1);
  5. kanna

    “serial”: “123456”,
    “headers”: {
    “Authorization”: “Signature keys=\”/smarId/hello/1234.123445\”,signature=\”””

    I want only */smarId/hello/1234.123445* as environment variable

    1. ppolyzos

      If only the Signature keys change, then you can do the following:

      var signatureKey = "/smarId/hello/1234.123445";
      pm.environment.set('AuthToken', `Signature keys=/"${signatureKey}/", signature=\""`); 

      You can learn more about string interpolation and template literals in this link

    1. ppolyzos

      Let’s assume you have this request from OpenWeather API:

      curl --location --request GET ''

      To access the ETag value you can use the following code in Tests panel:

      pm.response.headers.find(c => c.key === 'ETag').value

      For more info on postman’s response API you can have a look here

  6. Udhaya

    Hi I am new to postman, can we write JSON object in pre-req?
    and use this in the body?

       "Name":"Some Name",
      " Phone":"Some Phone Number"
    1. ppolyzos

      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:

      var address = {
          "Name": "ome Name",
          "Phone": "Some Phone Number"
      pm.environment.set("address", JSON.stringify(address));

      Step 2: In Body use that variable in your object:

      	"address": {{address}}

      Note the `{{}}` which are used in order to use this variable.

      postman set object in request body through environment variable

  7. Aditya

    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 :

    var authServiceUrl = pm.environment.get('authService');
    var gatewayBaseUrl = pm.environment.get('gatewayBaseUrl');
    var granttype = pm.environment.get('grant_type');
    var sdk = require('postman-collection');
    var isValidTokenRequest = new sdk.Request({
        url: gatewayBaseUrl + "/api/vendor-catalog/v1/datasources/categories", 
        method: 'GET',
        header: [
            new sdk.Header({
                key: 'Authorization',
                value: 'Bearer ' + pm.globals.get("jwttoken"),
    pm.sendRequest(isValidTokenRequest, function (err, response) {
        if (response.code === 401) {
    function refreshToken() {
        var tokenRequest = new sdk.Request({
        url: authServiceUrl,
        method: 'POST',
        header: [
            new sdk.Header({
                key: 'content-type',
                value: 'application/json'
        Headers: {
         Key : 'grant_type',
         value : 'client_credentials'
      pm.sendRequest(tokenRequest, function (err, response) {
          if (err) {
              throw err;
          if (response.code !== 200) {
              throw new Error('Could not log in.');
          pm.globals.set("jwttoken", response.json().token);
          console.log('New token has been set: ${response.json().token}');
    1. ppolyzos

      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:

      pm.globals.set("jwttoken", response.json().token);

      Your code looks fine, so I bet you might have missed something while accessing or setting global values properly.

      1. Aditya

        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.

          1. Aditya

            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

  8. Aditya

    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 :

    	    "name": "{{categoryName}}",
    Code : Pre-request Script
    var random1="{{$randomLoremWords}}";
    var random2="{{$randomLoremWord}}";
    var categoryName=pm.environment.get("name");
    var categorynameKey=pm.environment.get("nameKey");
    pm.environment.set("name", data[0].categoryName);
    1. ppolyzos

      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:

      postman random values per request

  9. Divanshu

    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”: “”,
    “password”: “abcdf123”

    1. ppolyzos

      If you just want the `DeviceId` from your response, you can create a test and use the following quick & dirty way:

      var data = JSON.parse(responseBody);
      var deviceId = connection.split(';').filter(a => a.indexOf("DeviceId") >= 0)[0].split('=')[1]
      pm.environment.set('deviceId', deviceId)

      One advice though, you should avoid sending sensitive data in your API responses, not a very good practice.

      Hope I helped 🙂

  10. B Ravi Raju

    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?

    1. ppolyzos

      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

  11. Roshin

    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

    let response = pm.response.json();
    pm.environment.set("transactionId", response.transactionId);
        "status": true,
        "statusCode": "PP0000",
        "statusText": "Success",
        "data": {
            "transactionId": "5fe4726c1ea03379ffcdcfea",
            "consumerMessage": "",
    1. ppolyzos

      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”,;`

  12. Techlinks

    How do you select the value of EntityToken from the JSON response below?

        "code": 200,
        "status": "OK",
        "data": {
            "EntityToken": "M3x7ImkiOiIyMDIxLTA3LTMxVDA2OjE1OjM2Ljk3ODMzMjRaIiwiaWRwIjoiVW5rbm93biIsImUiOiIyMDIxLTA4LTAxVDA2OjE1OjM2Ljk3ODMzMjRaIiwiaCI6IjU3QkIxMDQ4NTY4RDQyODkiLCJzIjoiYy92M0FqMUs3YmNqdWs5VVZpeWUxcHd0NVlBUm95TTRSV2hoYkhkUDg5bz0iLCJlYyI6InRpdGxlITk0MkMzQ0I4NzFCMUNGODAvNTJCQjUvIiwiZWkiOiI1MkJCNSIsImV0IjoidGl0bGUifQ==",
            "TokenExpiration": "2021-08-01T06:15:36.978Z",
            "Entity": {
                "Id": "52BB5",
                "Type": "title",
                "TypeString": "title"
    1. ppolyzos

      You could parse your response and then you access the nested property `EntityToken` as you would do in any json object:

      var data = JSON.parse(responseBody);

Leave a Comment

Your email address will not be published. Required fields are marked *