Set a variable from raw text response

Hi
I am using a legacy API that following authentication via a login API returns a session id in plain text in the response body that is needed to authenticate subsequent API calls . I have been searching and trying for two days to find a way to set this value into a “session-id” environment variable without success. Have found loads of examples of JSON and nested values but no idea how to set it using the response body which is 69 characters but with no markup. I am not a developer and really struggling so any help appreciated.

I have tried the following but no idea what to put for the “variable_value”

pm.environment.set(“session-id”, “variable_value”);

Hey @heath.dickinson,

Welcome to the community!! :wave:

Would you be able to post an example of the response and what value you would like to set please?

To get the response in text form, you can use pm.response.text(), depending on what part you would like to store, you can use basic JS to cut this down to the required value.

If the response is in the form you need already, you just need to add this to the Tests tab to capture the value and an environment variable.

pm.environment.set("session-id", pm.response.text())

The variable {{session-id}} can then be used in the desired request. In this example, I’ve just used the as a URL param but it can be used anywhere the {{...}} syntax is accepted.

2 Likes

Thank you. I did manage to get it working late last night with pm.environment.set(“session-id”, responseBody);

Where I was going wrong was I had quotes around the value with everything I had tried before.

Cool - Glad you found a solution that works! :trophy:

Although responseBody is something that can be used. I would suggest using the newer pm.* API to get the response body data.

Either pm.response.json() for JSON or pm.response.text() if you need just the raw plain text.

More about the pm.* API and the functions that can be used can be found here:

https://learning.postman.com/docs/postman/scripts/postman-sandbox-api-reference/

thank you. have changed to the pm api and works great.

1 Like
const echoPostRequest = {
  
  url: pm.environment.get("local") + '/login',
  method: 'POST',
  header: {
      'Accept': 'application/text',
        'content-type': 'application/json'
    },
  body: {
        mode: 'raw',
        raw: JSON.stringify({ 
            username: pm.environment.get("username"), 
            password: pm.environment.get("password")
             })
    }
};
pm.sendRequest(echoPostRequest, function (err, response) {
    pm.environment.set("token","Bearer "+ response.text());
});

salvou minha vida kkk