user19560879
user19560879

Reputation:

Saving a Postman collection variable from the response body

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"
        }
    ]
}

Upvotes: 17

Views: 31398

Answers (8)

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.

Upvotes: 0

Omid
Omid

Reputation: 294

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

Upvotes: 0

Phairat Kaewkandee
Phairat Kaewkandee

Reputation: 1

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

Upvotes: 0

Jun
Jun

Reputation: 3044

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);  
})  

Upvotes: 0

safineh
safineh

Reputation: 161

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);
});

Upvotes: 0

leo
leo

Reputation: 131

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.

Upvotes: 13

Miebaka
Miebaka

Reputation: 295

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

Upvotes: 1

Malsha Liyanage
Malsha Liyanage

Reputation: 236

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

Upvotes: 21

Related Questions