Saving a Postman collection variable from the response body
Asked Answered
B

8

14

Trying to figure out why I cannot get this to work? Also, console does not give much of a result.

Scenario:

  1. Making the POST request to get the response with TOKEN
  2. Save the response token to collection variable (as the collection file will be used for importing to another testing solution in the cloud)
  3. Using that collection variable to log out from the session

So, I need to be able to store this as a collection variable and use that token when logging out from the session/DELETE the API admin session.

Error in the console:

There was an error in evaluating the test script: JSONError: Unexpected token 'o' at 1:2 [object Object] ^

Tests:

var response = pm.response.json()
var jsonData = JSON.parse(response)
pm.collectionVariables.set("token", jsonData.response.token);

Response body:

{
    "response": {
        "token": "***"
    },
    "messages": [
        {
            "code": "0",
            "text": "OK"
        }
    ]
}
Barocchio answered 29/9, 2022 at 9:2 Comment(2)
You don't need this line var jsonData = JSON.parse(response) as the first line is parsed already. Then update the reference to the value to the correct variable name.Mummery
Alright. This did help. :) Thanks, and I would suggest you to make this as an answer. :)Barocchio
W
18

JSON.parse(responseBody) always gets a json representation of the response.

A complete fail safe approach would be:

pm.test("response is ok",  ()=>{
    pm.response.to.have.status(200)
})

var jsonData = JSON.parse(responseBody);

postman.setEnvironmentVariable("token", jsonData.token);
Wheels answered 29/9, 2022 at 11:0 Comment(3)
@x0nomad hope this answer helpsWheels
Thanks! This is a better, of course. Tested, works. ;)Barocchio
Please don't use that code, it's using the older variable set and parsing syntax. You had the correct code, you just didn't need to parse it again.Mummery
H
11
if(pm.response.code == 200){
    pm.environment.set("variable_name",pm.response.json().field_name)
}

variable_name is the name of the variable setup in the Environment and field_name is the name of the field or property in the response from a GET, POST or any method.

Houchens answered 20/4, 2023 at 21:15 Comment(1)
where can I put this code?Realgar
G
1

Here's the approach i used.

  1. Send the request
  2. Check if there response is 200
  3. If it's true set the token
pm.test("response is ok",  ()=>{
   if( pm.response.to.have.status(200)){
var jsonData = JSON.parse(responseBody);

postman.setEnvironmentVariable("token", jsonData.token);
}
})

You need to change your status code depending on the condition.

Hope it helps

Glossy answered 10/1, 2023 at 16:38 Comment(0)
L
0

I prefer pm to postman because pm is newer and postman may be deprecate.

a test code using pm:

pm.test("Save the new token to environment", function () {
    var data = pm.response.json();
    pm.environment.set('token', data.token);
});

A complete test script could look like this:

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

pm.test("Response has required items", function () {
    pm.expect(pm.response.json()).to.be.an('object').that.has.all.keys('response', 'message', 'token');
});

pm.test("Save the new token to environment", function () {
    var data = pm.response.json();
    pm.environment.set('token', data.token);
});
Lye answered 27/2 at 11:25 Comment(0)
F
0

You can put this code in the Tests section which is right next to Pre-request Script.

pm.test("save environment variable", ()=> {    
    pm.response.to.have.status(200)    
    var response = pm.response.json()  
    pm.environment.set("variableName", response.key1.key2);  
})  
Frons answered 27/3 at 8:11 Comment(0)
C
0

new update:

//data example
      {
            "success": true,
            "message": "User logged in.",
            "result": {
                "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIsInVzZXJuYW1lIjoiSkpKIiwicm9sZSI6ImFkbWluIiwiaWF0....NzE2Nzg0Mzc3LCJleHAiOjE3MTkzNzYzNzd9.8aQx4ffao4rs-850auJHRKcs9HMqougaM2uLmYfQxqU"
            }
        }

use:

var jsonData = JSON.parse(pm.response.text());
pm.collectionVariables.set("accessToken", jsonData.result.accessToken);
Cylindrical answered 27/5 at 4:56 Comment(0)
I
0

The best solution can be this one. Because you can check if the response is 200 then try to parse the response. Also it doesn't use the deprecated solutions

pm.test("response is ok",  ()=>{
    pm.response.to.have.status(200)
})

var jsonData = pm.response.json();

pm.collectionVariables.set("token", jsonData.token);
Imamate answered 5/8 at 13:42 Comment(0)
H
0
pm.test("Check response success", () => {
    const isSuccess = pm.response.to.have.status(200)

    if (!isSuccess) return

    const response = JSON.parse(pm.response.text())
    pm.environment.set("token", response.token)
})

Can replace response.token by other data structure depends on your API response.

Hilary answered 23/8 at 3:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.