Help with chained variable request please

I’ve been following this thread (and a few others):

Extracting Data from Responses and Chaining Requests | Postman Blog.

and was able to successfully extra my token from the results into a variable.

I am able to able to view the variable in the Quick Look Window as shown in step 2.

I am unable to successfully use that variable in my Gets as shown in step 3.

The response of my Authentication post is:
{
“access_token”: “LongStringOfTextHere”,
“expires_in”: 3600,
“token_type”: “Bearer”,
“scope”: “api.read api.write”
}

and this is the body:
var jsonData = JSON.parse(responseBody);

postman.setEnvironmentVariable(“ReThinkProductionToken”, jsonData.access_token);

If I hover over the Quick Look window I get the variable varReThinkProductionToken and it is populated with the value of the returned Access Token (as expected).

When I call my “Get” as such:
https://api.rethinkbehavioralhealth.com/api/v1/Appointments/12345

It works if I manually copy and paste the Bearer token into the authorization section. But it isn’t chained, and must be updated each time the auth expires.

Following the step 3 directions on the link above, I wen to the Body section, then chose form-data.

I then created a key named “token” (I have also tried “access_token” and “Token”) and when I type into the Value box, I am prompted for my variable ( {{varReThinkProductionToken}} ) and choose it.

When I press send I get a 401 unathorized error, unless I go to the Authorization tab and paste the real token value into the Token field. The drop down for type is Bearer Token, if that matters.

What am I missing?

If you have successfully extracted and saved the token.

All you need to do in the subsequent request is set the bearer token as follows.

Are you new to Postman, as you also seem to be using the old Postman API calls, instead of the pm API.

For example, to parse the response, you can put…

var jsonData = pm.response.json();

Setting an environment variable…

pm.environment.set("bearerToken", jsonData.access_token)

If you are new to Postman, I would recommend a visit to the Learning Centre.

If you are new to Postman I would recommend the Postman training links which are located under “Resources” in the Learning Centre.

Resources | Postman Learning Center

The “Galaxy API’s 101” course gets you used to sending requests and the GUI.

The “Galaxy Testing and Automation” gets you used to testing your responses and using variables, basic scripting, etc.

Finally, Postman uses JavaScript under the hood, If you are going to be scripting, I would also recommend learning some JavaScript basics. WC3 schools is a good place to start.

Finally, here is a more advanced script that can be used to retrieve your bearer token. It also deals with token expiries, so it doesn’t get a token every single time. Only when needed. It’s authenticating against Microsoft, but you should be able to amend accordingly.

let currentDateTime = Date.now();
let tokenExpiry = pm.environment.get("bearerTokenExpiresOn")
// console.log("currentDateTime: " + currentDateTime);
// console.log("tokenExpiry: " + tokenExpiry);
if (!pm.environment.get("bearerToken") || currentDateTime > tokenExpiry) {
    pm.test("Pre-request check for Environment Variables", function () {
        let vars = ['clientId', 'clientSecret', 'tenantId', 'username', 'password', 'scope'];
        vars.forEach(function (item) {
            // console.log(item);
            pm.expect(pm.environment.get(item), item + " variable not set").to.not.be.undefined;
            pm.expect(pm.environment.get(item), item + " variable not set").to.not.be.empty;
        });
        pm.sendRequest({
            url: 'https://login.microsoftonline.com/' + pm.environment.get("tenantId") + '/oauth2/v2.0/token',
            method: 'POST',
            header: 'Content-Type: application/x-www-form-urlencoded',
            body: {
                mode: 'urlencoded',
                urlencoded: [
                    { key: "client_id", value: pm.environment.get("clientId"), disabled: false },
                    { key: "scope", value: pm.environment.get("scope"), disabled: false },
                    { key: "username", value: pm.environment.get("username"), disabled: false },
                    { key: "password", value: pm.environment.get("password"), disabled: false },
                    { key: "client_secret", value: pm.environment.get("clientSecret"), disabled: false },
                    { key: "grant_type", value: "password", disabled: false },
                ]
            }
        }, function (err, res) {
            if (err) {
                console.log(err);
            } else {
                pm.test("Pre-request Microsoft login Status code is 200", () => {
                    pm.expect(res).to.have.status(200);
                    let resJson = res.json();
                    // console.log(resJson);
                    pm.environment.set("bearerToken", resJson.id_token);
                    pm.environment.set("bearerTokenExpiresOn", Date.now() + resJson.expires_in * 1000);
                    // console.log("bearerTokenExpiresOn: " + pm.environment.get("bearerTokenExpiresOn"));
                });
            }
        });
    });
};