Extracting Data from Responses and Chaining Requests

 

Update: If you want to dig deeper into chaining requests, check out our related post called How to Make Money Using Postman: Chaining Requests.


Postman lets you write scripts that run before/after you receive a response from the server. You can do practically anything in these scripts. The pre-request and test scripts run inside a sandbox and Postman enable the Postman object to interact with the main Postman context.

This opens up a number of new possibilities. One of them is extracting values from the response and saving it inside an environment or a global variable. Environment and global variables let you keep track of everything that affects the APIs state. Some examples of common variables you would use with an API are session tokens and user IDs.

The flow while working with variables currently goes like this:

  1. Send a request from Postman
  2. Receive the response and select and copy a value from the response body or the header
  3. Go to the environment manager
  4. Set the variable value
  5. Hit submit

This works, but is a lot of work if you have more than a few variables. Test scripts dramatically simplify this flow. All you have to do is call postman.setEnvironmentVariable(key, value) or postman.setGlobalVariable(key, value) to set a variable with values you have extracted from the response. You can even add something dynamically generated through Javascript.

Lets go through an example which will illustrate this in more detail:

1. Create and select an environment

For this example, we’ll create and set a blank test environment.

Screen Shot 2016-06-25 at 05.10.53

2. GET request to get response body

This request returns a JSON body with a session token. For this dummy API, the token is needed for a successful POST request on the ‘/status’ endpoint. To extract the token, we need the following code.

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", jsonData.token);

Add this to the test editor and hit send. Hover over the quick look window (q) to check that the variable “token” has the value extracted from the response

Screen Shot 2016-06-25 at 05.11.20

3. POST request with the previous session token

To send the token, we need to set it as part of the POST request. Let’s add a form-data variable to the ‘/status’ request.

Screen Shot 2016-06-25 at 05.12.01

On hitting send, Postman sends the token along with the request.

Test scripts let you extract variables and chain together requests in any way you like. As request variables work everywhere, you can build a sequence of API calls which exactly mirror your use case.

You can download the sample collection and import it inside Postman. Check out the docs for more Postman features. There are more tutorials planned in this series. Keep a tab on this blog as well as the Twitter account for more tips and tricks.

Tags:

What’s your experience working with test scripts? Leave a comment to let us know.

Comment

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


This site uses Akismet to reduce spam. Learn how your comment data is processed.

139 thoughts on “Extracting Data from Responses and Chaining Requests

    Works fantastic! This is a HUGE feature that I have yet to see any other REST client offer. Saves so much time. What isn’t clear to most when they use any rest client is the amount of time spent copying and pasting response values into other requests, especially in a HATEOAS based API where you need to follow link response hrefs to complete various REST API scenarios. What is also not clear to most when they first start using POSTMan is that this feature not only saves time for yourself, but you can SHARE the collection with your team! This is another huge time saver.. a QA engineer, or a developer, can come up with the various requests, the JS to pull values from responses, save it in a collection and typically the only thing anyone needs when downloading and using the collection is the API entry point. That assumes of course a farily good HATEOAS based API (or similar) that is built from a specific entry point in to the API so that the chained requests/responses can work correctly.

    Only thing I might add is more folder levels. It’s not difficult to manage without, but a couple more levels of folders would allow a sort of /// kind of layout, or something similar. I suspect it wouldn’t be hard to add in two or three more levels of folders, but as it is now it’s a massive time saver for teams that are developing and testing REST APIS!

    Well worth the $10 to add this capability!

      Thanks Kevin!

      SoapUI has had this feature since the beginning with the Property Transfer object. Which is actually more direct than this, which requires shuttling values off to env/global variables for temporary storage, which can result in a big spaghetti of temporary variables in your environment.

    Sometimes for my purposes I want to run a batch and extract data. I’d love to dump it to a file. Is this possible?

      Dumping data to a file would not be possible right now. But you can run batch requests and extract data.

        Thanks. I saw one example that had a console.log statement. But I can’t find the output in Chrome’s console output. Where does this output go or am I just failing the write the cmd right? Here’s what I have:

        var data = JSON.parse(responseBody);
        tests[“User ID”] = data.user_id;
        console.log(“USERID:” + data.user_id) // I tried a few variations of this

        I did not see any output in the chrome console log.

        p.s. I was hoping that the tests array printout would show the text I sent to it – that would be ideal but no luck 🙁

    This is a huge feature, and we’ve started to use this to produce test suites for specific bugs that work across test environments. One thing that this Blog does NOT mention that is equally huge is that these environment variables are not only available in the URL path or query arguments, but also in POSTED JSON STRINGS (for create() APIs, for example). I’ve already mentioned it to Abhinav, but I thought I’d put it here as well. It’s a very powerful feature!

      Thanks Steve! Will be making that clear in the next article.

    Actually, there is a large write up on API Chaining here (https://github.com/orubel/grails-api-toolkit/wiki/API-Chaining) with working functionality, apidocs, webhooks and role checking.

      That’s a nice article series. Thanks!

        Hi Orubel,
        HOw to get Global variable from CSV and use in Json(TestEditor) using collection runner. Need help
        My expected result is in CSV and I want to match with Actual result(variable of response body)
        Thanks

          You can use globals.my_variable_name to access variables. Check out the docs: http://www.getpostman.com/docs/ for more details.

            And how to get Environment variables and put in TestEditor?
            I am able to do for Global variable like globals.parameter.. Can we do for environment variable

            environment.parameter

          Thanks..I got it..Great help

      The link no longer works 🙁

        Code is being considered by VC. Has been made private and licensed changed.

    When I’m using the environment variables for the tests, these end up being written in my current environment right? This make my environment “dirty”. Is there any other way to pass variables between tests?
    I tried to use global variables but the effect is the same. Is there a way to pass this info around and don’t alter the current environment?

      Not yet. You can create a duplicate environment to make sure the original one isn’t affected.

    Is it possible to access a session cookie from the response in a collection runner? Login in and firing the request manually works fine. But running several requests in a collection will not recognize the returned session cookie.

      You should be able to access the Cookie header when you are using the Interceptor: https://blog.postman.com/index.php/2014/03/03/postman-v0-9-8-capture-requests-and-improved-response-rendering/

        I did, but I dont know how to access it with which postman dictionary. Cannot find an explanation. I see the cookies in the postman UI.

        I also need to use the cookie for my auth headers to run a collection. Is it possible to extract the session ID, stored in the cookie, for use in the auth header?

        I also need to access the cookie to chain the request for authentication. Is this possible? I don’t see ‘Cookie’ as part of ‘responseHeaders’. Is there a dictionary for this?

        I need this as well. Has anyone figured out how to access the cookies from a test and assign it to an environment variable?

        Currently there is no way to access cookie header inside test. This would be very useful feature, for example to be able to confirm that server sent correct cookie in response.

    HI Guys,
    Can we print Global variable of suite in Testoutput of Json testcase?
    I have defined one variable “URL”, It is working while sending the request but when I used in Testeditor and try to print {{URL}} then nothing is displayed.
    Please help me.

    HOw to get Global variable from CSV and use in Json(TestEditor) using collection runner. Need help

      My expected result is in CSV and I want to match with Actual result(variable of response body)

    Hello,

    I have been using this and it works great, however I need to take it a step further. For example:

    {
    Uuid: “”,
    expires: “”,
    language: “”,
    questions:[
    {
    choices[“”,””],
    questionUuid:”foo”,
    category:””
    }, …]

    I need to get the questionUuid value “foo”. How would I go about doing this?

    I have tried postman.setEnvironmentVariable(“questionUuid”, output.questions.questionUuid[0]); with no luck.

      postman.setEnvironmentVariable(“questionUuid”, output.questions[0].questionUuid);

    How I can use dynamic data in json using postman. For example I used “name” field dynamically so how I can use? Please suggest some code so I use with my script.

    How would I save binary data from a response to a variable, I’d like to then convert it from 4 byte hex to decimal, is this possible with PostMan and JetPacks?

    Hi,
    Is there any way to validate the data like

    response.facets.value === abc.stp

    and also facets.count === 29

    Below is the response which comes after hitting url with GET method

    {
    “records”: {}

    “start”: 0,

    “limit”: 5,

    “count”: 72,

    “accept”: “accept/header+json”,

    “limited”: false,

    “version”: “1”,

    “facets”: [

    {
    “name”: “type”,

    “results”: [

    {

    “value”: “abc.stp”,

    “count”: 29

    }
    {

    “value”: “Test”,

    “count”: 1

    }

    ]

    },

    {

    “name”: “User”,

    “results”: [

    {

    “value”: “User1”,

    “count”: 28

    },

    {

    “value”: “user2”,

    “count”: 17

    }

    Thank u…

    Sample collection is no longer available.

    Hi I’m testing the jetpack test runner. I’m stuck with this issue. Basically I need to input a unique email in body of every registration request. I’m using dynamic variable to make this unique. However I have to pass this email value in another request. I’m not able to extract and store the value from the request body unlike from the response.

    Like I can parse responseBody, I would like to parse requestBody. This is not allowed currently. Can you suggest any other workarounds?

      Hi @satish, my workaround is like so:

      “`
      var requestBody = postman.__execution.request.body.raw;
      “`

      You can parse the JSON, using `JSON.parse(requestBody);`

    Hi there. Can i use the saved variable (token) in GET requests’s header?

      Yup! Just use ” {{TokenName}} “

    The link to the sample collection

    https://www.postman.com/collections/f85c7dedaabe1492648f

    returns “sample not found”

    Hello there. Could you please help me in understanding how to parse a responsebody (json)
    so the data from [] is also can be used.
    Cause when i use var data = JSON.parse(responseBody)
    it parses only the data that is situated in {}, but the data from [] can not be used.
    And the environment variable is set as ‘undefined’
    Thanks,

      [] signifies an array. so you’ll need to parse that out. i.e.
      data.body.Array[0].element

        cyclistmetrodetroit Abhinav Asthana
        What I am trying to do – parse through JSON response which has an array and from array fetch value of an element which appears more than 1 and save it in environment variable.
        Here is the response body for reference –
        {
        “key1”: “valueofkey1”,
        “key2”: “valueofkey2”,
        “arrayname”:
        [
        {
        “arraykey1”: “value1”,
        “arraykey2”: “abc”,
        },
        {
        “arraykey1”: “value2”,
        “arraykey2”: “abc”,
        }
        ]
        }

        Here is what I am doing –
        var data = JSON.parse(responseBody);
        postman.setEnvironmentVariable(“envvarname”,data.arrayname[0].arraykey1);

        It is always saving value1 in environment variable.

        Can you provide me solution which will save value1 and value 2 under envvarname.

        My next question is – Once envvarname has more than 1 value saved, how will the API consuming envvarname be able to execute picking it’s value one by one.

    The link to the sample collection isn’t working? Any other place I can find this collection?

    how we can extract report of Pass/failed results from POSTMAN tool. I am using trial version.

    Abhinav – is it possible to add Request Chaining in the free version ? This seems like a basic feature similar to what jMeter also provides .. not sure if Insomnia has it ..

      I don’t think any other REST client has Postman’s testing capabilities. 🙂

      We will share some news soon on request chaining capabilities. Keep checking the blog!

        eagerly waiting 🙂

        Hi Abhinav,
        How to print the value from return response body

    If I get a JSON response I can easily parse it with JSON.parse(responseBody).

    But what if I want to parse an XML or HTML?
    – XML.parse(responsebody) doesn’t seem to work
    – var xmlparse = postman.findElementById(“theId”); doesn’t seem to work…

      Hey, you can use the xml2Json method to parse XML to JSON.

      
      var json = xml2Json(responseBody);
      

    Hey, this is really a useful feature. I just noticed that it is made available to the free users now.

    Is it possible to use the environment variable as the resource id in the URL itself? For example, is it possible to use the id (say uid=1234) of the resource that was created and returned from one request, and use it in the next request url, like this : localhost/api/v1/users/ (uid=1234)?

    Hi Guys , Can you please send me an example about how to extract the
    data if my response is XML? I am trying to get the field named “id” to
    use it later. Thanks,

      You can use the xml2Json method to convert an xml string to an JSON object.
      If your response body is an XML, you can do this in your test

      
      var responseJson = xml2Json(responseBody);
      console.log(responseJson);
      

      For the xml string in your comment, you’ll get an JSON object like this –

      
      {
          "createResponse": {
              "$": {
                  "id": "2211504",
                  "type": "Payment",
                  "xmlns": "URL/"
              }
          }
      }
      

      You can have a look at the documentation for more things you can do in the pre-request scripts and tests.

        I converted it to JSON, but how would one go about verifying the log? I’ve enabled Chrome Dev Tools, but where in the inspection panel would the output be pushed to the console?

          unsuscribe

          Am 10.05.2016 um 15:55 schrieb Disqus:

          I managed to resolve this issue – I needed to drill down further into the Json object. To answer my own question, you verify the log by Inspecting the Runner, and clicking the Console tab in Chromes Dev Tools

    Hi guys,
    Can I download a zip file from response and store somewhere (local disk)?
    thanks

      Is there any solution to this?

      Michal, did you found a way to download the zip file?

      I actually can do this through “Send and Download” but the downloaded file seems that is not extracting correctly. Maybe it is a decoding issue. Is there any way to check this?

      Actually you can download the zip file through “Send and Download”.
      But for my case, the downloaded file seems that is not extracted correctly. I do not know if this is a decoding issue.
      Is there any solution to this?
      Michal, did you also face this issue?

    Hi All, can anybody help with response parsing. In response i get only a digit like “30”? how can i parse it to use in next requests? Thanks

    Hi

    I have a response like:
    {
    “totalPrice”: 3700,
    “originalTotalPrice”: 3700
    }

    I want to extract the total Price and use this in another request, but first I want to make sure the price is correct so I use a test like this:

    var data = JSON.parse(responseBody);
    tests [“Verify originalTotalPrice”] = data.totalPrice===3700;

    This always fails for me and I’m not sure why. Is there any way for me to see what it thinks the value of totalPrice is?

    If I change the test to tests [“Verify originalTotalPrice”] = data.totalPrice=3700;

    it always passes but I can set the number to anything, so its obviously not correct.

    Thx

    Nick

      You’re doing assignment here, not comparison. “=” assigns. “==” or “===” compares. If you’re expecting a whole number, try:
      tests[“Verify..”] = parseInt(data.totalPrice) == 3700;

      See if that works.

      Hi Nick ,

      I am also facing same problem , did you get solution for your query?

      var data = JSON.parse(responseBody);
      tests [“Verify originalTotalPrice”] = data.totalPrice===3700;
      if you get answer , please share it to me

    How can i use this:
    postman.setEnvironmentVariable(“x-auth-token”, data.x-auth-token);

    I think the “-” is causing me issues

      Just worked through this myself, heres what I put in place:

      var response = JSON.parse(responseBody);
      postman.setEnvironmentVariable(‘x-auth-token’,response.data.x-auth-token);

    So I’ve assigned my token string to an envir var as follows:
    var respBody = JSON.parse(responseBody);
    postman.setEnvironmentVariable(“token”, respBody.accessToken);

    and in my subsequent GET request, I add the “Authorization” header with the value of {{token}} .

    However, I’m getting NOT AUTHORIZED back in the response.

    Of course if I HARD CODE the token string, it works fine. But I NEED to use the environmental var for this.

    Any ideas ?
    thanks.
    Bob

      Are you using the Postman runner? Or doing it one step at a time. You have to setup the environment and then run them as ordered tests.

      I am also getting the same issue. Hard coded token is working for me.
      But if i define token , am getting error as below.
      there was an error in evaluating the test script : token is not defined

      var jsonData = JSON.parse(responseBody);
      postman.setEnvironmentVariable(“token”, jsonData.token);
      console.log(token);

    Having trouble just grabbing an html element from the response.

    I can see the element in the response visually:

    but trying to grab it with either $(“.csrf_token”) or document.GetElementById(“csrf_token”) are both throwing back nulls. Is there anything special I need to do to be able to parse the response in postman for an input element?

      You’re getting the response as a string in `responseBody` variable and it is not attached to the document for you to be able to extract elements like the way you mentioned. You could convert XML to JSON and work on it.

      In Postman app you could also try and load the HTML using jquery – first do var responseHTML = $(responseBody); and then do responseHTML.find(‘.csrf_token’).

      Note that jquery will not work predictably with Newman (the CLI of Postman)

      You could also try getting in touch with others in our Slack Postman community for help – mail us at [email protected]

        I got it wouthout Jquery eventually doing something similar to what you suggest:

        var responseHTML = document.createElement(“html”);

        responseHTML.innerHTML = responseBody;

        inputs = responseHTML.getElementsByTagName(“input”);

        console.log(inputs);

        token_element = inputs[0];

        console.log(token_element);

        value = token_element.value;

        console.log(value);

        postman.setEnvironmentVariable(“csrf_token”, value);

          This is perfect!

          When I run this I get “ReferenceError: document is not defined” did you not get the same?

    I am able to extract the a value from a JSON response.data[0].key to a variable. However how do I send this value to another request with a JSON request body (Raw format). ?

    The pre-request scripts are great BUT i’d like my authorization request to prompt for username and password (don’t want this sensitive credentials stored in the request and synced through Google). Unfortunately the JavaScript “prompt” function doesn’t do anything, is there another way I can prompt for user input before making a request?

    I need to get the SequenceNumber value and store as a EnvironmentVariable and so far no luck. Can some one help me? 270164614.

    var jsonData = xml2Json(responseBody); postman.setEnvironmentVariable(“SequenceNumber”, jsonData.Response.Field (not sure how to write this part)

    hi,we provide online training & video tutorial for soapui

    for free videos refer

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

    Hi Guys,

    I have an API URL which has the id which is dynamically obtained from the previous API URL executed and pass that response/result id to other API dynamically. So how could I achieve this by adding extracting the id from one API and pass the same as URL for another API

    written this in test

    var data = JSON.parse(responseBody); postman.setGlobalVariable(“casino_id”, data[‘id’]);

    second API request says ‘400 Bad request’

    and in environment for ‘casino_id’ it says ‘undefined’.

    Please help

    hI

    I am trying to automate testing for Bell.ca website. On one of the pages I have to press ‘Send code’ option button and whatever code it generate..i need to input in Verification code input field.
    So when I press Send code option In F12 -> network -> response I see that value in Response.data
    How can I extract that VerifyCode value from Response and input into my input field?
    I am uploading the SS to make it more clear.
    Your response will be highly appreciated.

    Hi All,

    My JSON is the form of {
    “soapenv:Envelope”: {

    “multiRef”: {

    “-soapenv:encodingStyle”: “http://schemas.xmlsoap.org/soap/encoding/”,

    “title”: {
    “-xsi:type”: “xsd:string”,
    “#text”: “soapf”
    },

    }

    }

    }

    How can i get value of “title”? Can anyone help me on this? This json is result of xml2Json conversion

      My response object is
      Object {
      soap:Envelope {
      soap:Body{
      ns2:createUserResponse{
      return
      :
      “2775”
      }
      }
      }
      }
      So I have used
      postman.setGlobalVariable(“userId”, jsonObject[‘soap:Envelope’][‘soap:Body’][‘ns2:createUserResponse’].return);
      to store the value in global variable.
      Hope it helps you

    I’m just getting into Postman and I’m enjoying learning what look like a hugely useful product.

    I have a two part question about selecting variables in the JSON returned in the first of a chained series.

    I have several product IDs returned in the JSON from my search query on my warehouse, e.g.:

    “productId: 124624A”
    “productId: 124624B”
    “productId: 124624C”

    These product IDs are system generated, so may change, making impossible to know what they are going to be in advance.

    Question One: How can I have Postman select the first productId it finds?
    Question Two: Can I also have it select, for example, the Tenth productId?

    My guess is I need to populate an array (using Javascript in the Tests tab) and hen select the “nth” from that (like “0” for the first item in the array).

    But is there an easier way? Just learning right now so I am using the community edition, not professional.

    How can ASP.Net Web API get response data from Postman?

    Quick Question (I might be doing something wrong here):

    I want to parse a key called test-date into an variable and use this in other requests.
    I think there is something wrong with json.Data.args.test-date. NOTE: Response cannot be changed for my tests.
    This is what I have written and it doesn’t work:

    var jsonData = JSON.parse(responseBody);
    postman.setEnvironmentVariable(“test-date”, jsonData.args.test-date)

    Response:
    {
    “test-date”: “Mon, 19 Sep 2016 08:39:35 EDT”
    }

      All we need to do is jsonData[“test-date”])

    Hi,
    I hava some Questions about Postman.How can i Decode the postman ResponseBody?please reply me as soon as possible.Thanks.

    Hello,

    1. Create one global variable named ‘ids’
    2. Create a POST method, add script in Test field:
    tests[“Successful POST request”] = responseCode.code === 201 || responseCode.code === 202;
    var jsonData = JSON.parse(responseBody);
    postman.setGlobalVariable(“ids”,jsonData.id);
    3. Send the POST, get response:
    {
    “data”: {
    “id”: 470595271655486,
    “type”: “staffSubstitution”,
    “accountId”: 8800387990610,
    “calendarId”: 884011643700845,
    “contactId”: 466197263641902,
    “createdDate”: “2016-10-14T09:48:55Z”,
    “createdId”: 884011643700659,
    “createdName”: ” zhang”,
    “lastModifiedDate”: “2016-10-14T09:48:55Z”,
    “lastModifiedId”: 884011643700659,
    “lastModifiedName”: ” zhang”,
    “resourceBundleId”: 888409690211244,
    “status”: “A”
    }
    }
    I need to get the ‘id’ value “470595271655486”.
    But I found the global variable is ‘undefined’, where is wrong?

    Hi
    My GET response is too long and my queries are as follow.
    1. How do i search the specific value from the response.
    2. Once i search the right node then I want to pass the “ID” from the GET response to PUT request. How do i do it ?
    Model in response is unique identifier.

    sample
    {
    “meta”: {},
    “links”: {},
    “linked”: {},
    “nodes”: [
    {
    “id”: “00d26b00-c31d-49db-8bcc-4da29794a9a2”,
    “userId”: “dc3044b6-59e4-4049-9568-5684b1ee4731”,
    “Model” : “a”
    “attributes”: {
    “state”: {
    “reportedValue”: “ON”,
    “displayValue”: “ON”,
    },
    {
    “id”: “00d26b00-KTXH-49db-8bcc-4da29794a9a2”,
    “userId”: “mb0987b6-59e4-4049-9568-5684b1ee4731”,
    “Model” : “b”
    “attributes”: {
    “state”: {
    “reportedValue”: “OFF”,
    “displayValue”: “OFF”,
    },
    ……..

    Please advise

    Hi,
    Iam getting same response from request . what is the issue? please help me out

    I’m trying to get “Id” from the below json response.

    [
    {
    “Id”:”abc”,
    “Name”:”George”
    }
    ]

      Hey, I am experiencing the same issue. Did
      you get the solution to this?

      var jsonData = pm.response.json();
      var ID = jsonData[“Id”];

    Very Helpful. One caveat that might worth mentioning, the
    jsonData.abc format can’t have special characters in the name. I was trying to
    grab a field name “token-id” and received a reference error.
    You can get it with
    jsonData[‘token-id’] instead.

    I want to publish the JSON message values against each tag into an external csv or xl file. can that be done once I have stored the values in different environment variables?

    I want to publish the JSON message values against each tag into an external csv or xl file. can that be done once I have stored the values in different environment variables?

    Hi everyone,

    I see that it is possible to save a value from Headers (not from Body) but I cannot figure out how. Can anyone give me an example on how to save the Date for example?

    Thank you

    Hello all, I am new to postman and i found the above comments very helpful. I also have the below query which someone can answer if it’s really possible in postman.

    I want to get more than one data from response (no.1) in postman response body and use them to compare with data in another response (no.2). Is it possible to save them somewhere and compare them in second response.

    My Json response looks like below –

    Response body:
    {
    “meta”: {},
    “links”: {},
    “linked”: {},
    “sessions”: [
    {
    “id”: “XXX”,
    “links”: {},
    “username”: “web_test_343”,
    “userId”: “123456”,
    “extCustomerLevel”: 1,
    “latestSupportedApiVersion”: “17”,
    “sessionId”: “XXX”
    }
    ]
    }

    And I want to send userid, session id and ex cusotmer level in my another request and want them to be compared in the response.

    Hello,

    I am exploring postman client, but I didn’t get any option to export request and its respective response after execution. either i have to export request separately or response but not together.
    So that we can use it as Proof of Testing and share it with client as well.

    Scenario is:

    1) Create few request (Get/Post/Put)
    2) Execute all request at a time or one by one
    3) Once execution is completed we should get request and its response in e external file for each request

    There is option available to export Request and response separately.

    Please suggest if any option is available with respect to my requirement.

    I hope you understood my requirement

    Hi,
    Is there any solution to set a variable into POST request body in json? I parsed some data from response and set it into variable, i want to set in to json.
    Thanks)

      Even I was facing the same issue, I resolved it with following JSON format for the POST request body:
      {“origin”:”uaa”,”type”:”GROUP”,”value”:”{{admin_groupId}}”}

    Hi,
    I am trying to pass variable value in the request as raw data. But facing issue. I am passing the request as follows:
    {“origin”:”uaa”,”type”:”GROUP”,”value”:{{admin_groupId}}}
    How to pass variable as value?
    Can any one give me the solution?
    Thank you

      Finally I got the solution with the following request:
      {“origin”:”uaa”,”type”:”GROUP”,”value”:”{{admin_groupId}}”}

    Hello,
    I am trying to extract a column values from excel to an array in postman.
    But I am unable to find the length of the column.
    Is there a way I can do this without using Iteration?
    Thank you,

    Hello,
    I extract “TransactionID” from response JSON body and store it in environment variable.
    But POSTMAN sets to env variable wrong value of TransactionID.
    For example,
    JSON.TransactionID =9990000003608044 –>env.TransactionID=9990000003608044;
    JSON.TransactionID =9990000003608045 –>env.TransactionID=9990000003608044;
    JSON.TransactionID =9990000003608046 –>env.TransactionID=9990000003608046;
    JSON.TransactionID =9990000003608047 –>env.TransactionID=9990000003608048.

    I use next script in Tests tab:

    var jsonData = JSON.parse(responseBody);
    postman.setEnvironmentVariable(“TransactionID”, jsonData.TransactionID)

    pm.test(“Status code is 200″, function () {
    pm.response.to.have.status(200);
    });

    pm.test(‘”SuccessFlag”:true,”ErrorID”:0,”ErrorInfo”:”OK”,”InternalErrorID”:0,”InternalErrorInfo”:”OK”,”TransactionID”:’+jsonData.TransactionID, function () {
    pm.expect(pm.response.text()).to.include(‘”SuccessFlag”:true,”ErrorID”:0,”ErrorInfo”:”OK”,”InternalErrorID”:0,”InternalErrorInfo”:”OK”‘);

    });

    Can somebody explain me what’s wrong with my script.

      Stackoverflow beckons, my son.

    [{
    “attribute”: “Description”,
    “oldValue”: null,
    “newValue”: “123”
    },
    {
    “attribute”: “Locker Name”,
    “oldValue”: null,
    “newValue”: null
    },
    {
    “attribute”: “Attribute62.Type”,
    “oldValue”: null,
    “newValue”: “User-provided”
    }]

    Need to extract “newValue” of “attribute”: “Locker Name”.

    If someone can help that would be great.

      var extractedValue;
      pm.response.json().forEach(function(item) {
      if(item.attribute === “Locker Name”) {
      extractedValue = item.newValue;
      }
      }

    Hi,

    Anyone help me to extract text data from response body of postmane. JSON.parse(responseBody); is for extract data which is in json format not in text format

    Thanks in advance.

    Hi, Abhinav!
    Thank you for this post!
    I’ve the one comment:
    postman.setEnvironmentVariable(“token”, jsonData.token); – this “older style” of writing Postman tests are deprecated (https://learning.postman.com/docs/writing-scripts/script-references/test-examples/)

    “New style”:
    pm.environment.set(“token”, pm.response.json().args.token);

    Amazing, this helps me a lot.

    I extracted the data and was able to use it in any “body” format

    Thanks a lot @Abhinav

    Hi, Thanks for this post. I’m having so many issues time to time on test scripting in postman. Even when I added same code for my test to get the token to set as environment variable, I’m getting “There was an error in evaluating the Pre-request Script: Error: Unexpected token ‘<' at 1:1 ErrorUnauthorized ^”. Trying all possible solutions and didn’t work anything.

      Thanks for reading and reaching out. We recommend posting this on the Postman community forum at community.postman.com so that you can receive help from more Postman users about the issues you’re encountering.

    I just used this trick it is awesome !

    I would like how to bind to a table – the response json in the tests tab so I can see the response from the Postman call in a more tabular way than just a json. I tried with this syntax but it doesn’t seem to bind, even though the response json is there…
    Here … is the excerpt from my setting in the Tests tab
    {{#each response}}

    {{investigator}}
    {{aevent}}
    {{iso_score}}
    {{is_anomaly}}

    {{/each}}

    `;
    // Set visualizer
    pm.visualizer.set(template, {
    // Pass the response body parsed as JSON as `data`
    response: pm.response.json()
    });

    I am facing a strange issue with postman chaining of requests I will explain my scenario below
    1. I am chaining POST and PUT request in a folder
    2. The response coming from POST request has a field which I am storing in environment variable and passing it as input parameter to 2nd PUT Request
    3. While running this folder (POST+PUT) through runner I am passing test data to 2nd request through a csv file where as for the first request we have hard coded request body.

    Issue:
    Getting incorrect response i.e., response populated for the 2nd request is same as response of 1st request.
    Steps tried to resolve:
    1. Verified the request body of 2nd Request- it is going correctly and my test data is getting picked from csv file
    2. Checked and unchecked the cookies option in runner
    3. Used Set Next request line in tests tab
    4. Manually tested the scenario without using chaining and csv files and it is working fine

    Could someone please help us with the above issue and how can we overcome this problem.

    Hi, Thank you for your know how sharing. It is good for me to catch the token from the Login service for using the Authentication value in the next service request.

    Im trying to figure out why my command is just returning “null” when trying to store to pm.environment

    {
    “result”: [
    {
    “parent”: “”,
    “shadow”: “false”,
    “sys_id”: “b59bd0991b1805105a7d21fcbc4bcbfe”,
    }
    ]
    }

    Good job guys, I’ve been thinking for a few days and finally found it.

    very helpful thanks

    is the syntax still supported with current version of Postman, or it’s here only for historical reasons:

    var jsonData = JSON.parse(responseBody);
    postman.setEnvironmentVariable(“token”, jsonData.token);

    this doesn’t seem to work when the body returns more than one item in the same node ??
    for example “company branches” : there will be more than one branch id

    Hi Abhinav, how to handle the response if the key is not present in the response and it has only the value. something like below,
    response:-
    [
    “43f00080-47a0-40c7-91db-ebaca3736128”
    ]

    As far as I understand iterations are not concurrent because if they do, the method of using a global variable for chaining data was pruned to data corruption.
    So it’s still not a viable testing tool but a dev tool.

    Hm… what about gRPC? How to get “important_value” from this response:
    (the answer from script pm.response.messages)
    { data:
    { one_more_data:
    [ { key: value,
    key: value,}]
    important_key: important_value,
    another_important_key: another_value,
    }
    }

    Can we do request chaining on 2 different URLs of an Api??

    thank you for this tiny solution, mine is working fine after slight change over script

    var jsonData = JSON.parse(responseBody);
    pm.environment.set(“token”, jsonData.token);

    Very nice, thank you! This greatly improves the workflow for our requests in Postman. A developer’s dream <3

    Good day!
    I can’t transfer the data received in one block (POST request). Which are needed as the basis for the block following it (POST request). I am writing about the variable {prospectiveSaleId} . As you can see in the screenshots…
    I need the resulting POST request response: https://api-…./prospectivesales/create/v4 ,
    part of the response, the {ProspectiveSaleId} variable. Use as a basis for the following query:
    https://api-…./prospectivesales/{ProspectiveSaleId}/postpone . However, the error sent by the server is: “message:”The value ‘{ProspectiveSaleId}’ is not valid.”
    Doesn’t let it dry out.
    Additionally, I set up the environment and variables. The screenshots also show that in the query string, I use the {{prospectiveSaleId}} variable. However, in this case, the server answers me with an error. And thus, does not want to use the value in the specified variable. As a basis of use for the next request.
    Question: How is it possible to transfer / use the received variable and its value as the next POST request?
    My first post:
    https://community.postman.com/t/transferring-data-from-one-block-to-another/50990
    And my second post “Thanks for reaching out to Postman Support!
    Your request 161223 has been received outside of our business hours.”
    It is necessary to supplement that on the pages of the site, and on this forum. I did not find an answer to my question. Please help me.

    Thanks ten years later! Still working, but some warnings from deprecated things. New way to step 2 (obtain response body) without warnings:

    var jsonData = pm.response.json();
    pm.environment.set(“token”, jsonData.token);