Search code examples
postmanpostman-testcase

In Postman, is there a way to persist request body values (as environment values)?


I am trying to chain a couple of API requests together and wanted to automate the values to be carried over in the chain. Request body for first request looks something like this

{
   :
   :
   "details":{
      "identifiers":[
          {
            "id": "1234", // ---> Am setting this manually, which I need in my 2nd request.
            "idType": "SpecialID"
          },
          {
             "id": "3456",
             "idType": "uninterestingID"

          }

       ]

    }

}

Note that

  • I want to use the value of id in the second request only if it is of idType "SpecialID"
  • The order of these two IDs may not be fixed
  • In some requests, "uninteresting" ID may not be sent BUT "SpecialID" will always be sent

Given the above conditions, how do I do this in a Postman test i.e. store the value of id in the request body of one API call and use that in a second API's request call ? If customer code is required, I don't see a way to do this in Postman.


Solution

  • If you really want to get the id from the object with the idType of "SpecialID" within the request body and save it to an environment variable, you can do the following.

    let body = JSON.parse(pm.request.body.raw);
    
    let specialID = (body.details.identifiers.find(obj => { return obj.idType === 'SpecialID' })).id
    
    pm.environment.set("id", specialID);
    console.log(pm.environment.get("id")); // 1234