Extracting data from responses and 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 provides 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 API 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.

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. And do get the Jetpacks upgrade!

UPDATE: Like this tutorial, and want to dig deeper? Check out the follow up: How to make money using Postman: chaining requests?

Author: Abhinav

CEO @ Postman

118 thoughts on “Extracting data from responses and chaining requests”

  1. 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!

    1. 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.

  2. 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?

      1. 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 🙁

  3. 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!

      1. 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)

          1. 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

  4. 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?

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

  5. 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.

      1. 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.

      2. 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?

      3. 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?

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

      5. 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.

  6. 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.

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

  8. Hello,

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

    Uuid: “”,
    expires: “”,
    language: “”,
    }, …]

    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.

  9. 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.

  10. 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?

  11. 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…

  12. 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?

  13. 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’

      1. 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”,
        “arraykey1”: “value1”,
        “arraykey2”: “abc”,
        “arraykey1”: “value2”,
        “arraykey2”: “abc”,

        Here is what I am doing –
        var data = JSON.parse(responseBody);

        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.

  14. 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 ..

  15. 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…

  16. 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)?

  17. 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,

    1. 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

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

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

      1. 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?

        1. 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

    1. 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?

    2. 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?

  18. 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

  19. 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.



    1. 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.

    2. 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

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

    I think the “-” is causing me issues

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

      var response = JSON.parse(responseBody);

  21. 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 ?

    1. 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.

    2. 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);

  22. 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?

    1. 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 – get your invite at https://www.postman.com/slack-invite or mail us at help@getpostman.com

      1. 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”);


        token_element = inputs[0];


        value = token_element.value;


        postman.setEnvironmentVariable(“csrf_token”, value);

  23. 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). ?

  24. 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?

  25. 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)

  26. 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

  27. 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

  28. 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.

  29. 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

    1. My response object is
      Object {
      soap:Envelope {
      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

  30. 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.

  31. 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)

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

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

  33. 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);
    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?

  34. 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.

    “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

  35. 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.

  36. 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?

  37. 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?

  38. 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

  39. 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.

  40. 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

  41. 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.

    1. Even I was facing the same issue, I resolved it with following JSON format for the POST request body:

  42. Hi,
    I am trying to pass variable value in the request as raw data. But facing issue. I am passing the request as follows:
    How to pass variable as value?
    Can any one give me the solution?
    Thank you

    1. Finally I got the solution with the following request:

  43. 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,

  44. 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.test(‘”SuccessFlag”:true,”ErrorID”:0,”ErrorInfo”:”OK”,”InternalErrorID”:0,”InternalErrorInfo”:”OK”,”TransactionID”:’+jsonData.TransactionID, function () {


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

  45. [{
    “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.

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

  46. 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.

Leave a Reply

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.