Home > database >  Saving a Postman collection variable from he response body
Saving a Postman collection variable from he response body

Time:09-29

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

Thank you very much for any advice!

CodePudding user response:

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.response.token);
  • Related