How to create a pre-request script for login endpoints that returns text token

Hello, I have two collections and each of them has one reqest that gets authentication token from separate APIs. The first one works great and it returns a Json with 3 properties.

{
    "access_token": "XXXXXXXXXXXXX",
    "token_type": "bearer",
    "expires_in": 3599
}

For other end point, I use the following pre-request script so I can consume them in one go:

const getTokenRequest = {
  method: 'POST',
  url: 'https://Example.api/v3/token',
  header: 'Content-Type:application/json',
  header: 'Accept:application/json',
  body: 'grant_type=password&username=username&password=xxxxxxx'
};

pm.sendRequest(getTokenRequest, (err, response) => {
  const jsonResponse = response.json();
  const newAccessToken = jsonResponse.access_token;
  pm.variables.set('Access_Token', newAccessToken);
});

Then I use the new variable “Access_Token” in the authorization tab for other endpoints that require authentication.

The above scenario works great. The second collection is the one I am having issues with. The token endpoint doesn’t return a json token with properties like the above. It just returns the text of the token. The following is the Api token end point

Method: Post
the url is https://Example.api/session/login
Headers:
                 Accept: application/vnd.v1+json
                 Content-Type: application/json
Body: 
          {"UserId": "userid","Password": "xxxxxxxx"}

It returns the token as just text

sdrlkfjgnsdlfndlfndslfnsdl
     kjhndsffgdflkjnbgdslkfgnSDGSDKNNJGJsdikjngdlfknsdfldksnfs

Any help is appreciated.

To get the text response it would just be:

console.log(pm.response.text())

I’m just logging it to the console here but you can save that value to a variable and use it in the same/similar way you have in previous requests.

Maybe something basic like this structure to use in an async request from a script:

pm.sendRequest({
    url: 'https://Example.api/session/login',
    method: 'POST',
    header: { 
        'headername1': 'value1', 
        'headername2': 'value2' 
    },
    body: {
        mode: 'raw',
        raw: JSON.stringify({ UserId: '1234', Password: 'itsASecret' })
    }
}, function (err, res) {
    pm.collectionVariables.set(res.text());
});

Hi Danny,
Thank you for you response.
I tried your suggestion but I am getting an error in the console. See attached image.

Any thoughts?

Ali

The request looks like it returned a 400 so I’m guessing that some part of it wasn’t sent correctly.

I have zero knowledge about the request you’re sending, apart from the example you have posted. I don’t know how it’s supposed to be structured.

Check the console and see what was sent in the body of the login request

What is strange is that If I call the login endpoint separately, it works and returns a token.

Ali

I don’t know what else you have tried in the script. What was the output in the console for the request body?

It’s going to work in the main request because you’re not sending it via the script, which would have a slightly different structure and most of those things been auto done for you already.

  • Try adding quotes around the key values?
  • Try removing the JSON.stringify() the body.

Basically, trial and error. I’m not sat there in front of this so I can only make suggestions of what I might do to solve that situation, I don’t have the ‘solution:grin:

I was just having issues on trying to do the same thing. Just resolved it with the following script.

var requestConfig = {
    method: 'POST',
    url: 'myEndpointUrl',
    header: 'Content-Type: application/json',
    body: {
        mode: 'raw',
        raw: JSON.stringify({
            "username": "admin",
            "password": "123456"
        })
    }
};

pm.sendRequest(requestConfig, function (err, response) {
    if (err) {
        console.error(err);
    } else {
        if (response.code === 200) {
            var responseBody = response.json();
            var token = responseBody.token;
            pm.collectionVariables.set('accessToken', token);
        } else {
            console.error('Failed to login. Response code:', response.code);
        }
    }
});

Hope it helps someone. :slight_smile: