Why is pm.sendRequest returning a function in 'response'?

Use case: Before making an API call, get the latest OAuth token and update it in the environment variable

(async () => {
try {
//Set environment variables and encode credentials

// Send POST request
console.log("Before sending request...");
const response = await pm.sendRequest({
  url: tokenEndpoint,
  method: "POST",
  header: {
    "Content-Type": "application/x-www-form-urlencoded",
    "Authorization": `Basic ${encodedCredentials}`
  },
  body: {
    mode: "urlencoded",
    urlencoded: [
      { key: "grant_type", value: "client_credentials" }
    ]
  }
});

console.log(ā€œResponse received:ā€, response); // Log the entire response object

// Check if response exists (optional)
if (!response) {
  console.error("Error: No response received from server.");
  return; // Exit the function if no response
}

// Code to read response and update the ā€œaccess_tokenā€ environment variable

} catch (err) {
console.error(ā€œError fetching new token:ā€, err);
}
})();

The log statement in bold prints that ā€˜responseā€™ is a function. Here is the exact message :

" Response received: :arrow_forward:{test: ā€œ[Function]ā€}"*

Because of this, I am not able to read any propertie from the response object.

Any idea what I might be doing wrong?

You need to parse the response.

Tried that already. Used response.json() and response.text() both to see if Iā€™m able to get through. I get an error

Error fetching new token:* :arrow_forward:{type: ā€œErrorā€, name: ā€œTypeErrorā€, message: ā€œresponse.json is not a functionā€}

So, in order to check what response is, i logged the entire response object and found out that it is a function

Are we talking of parsing it in any other way? I have tried reading the header too. That doesnā€™t work as well.

I donā€™t see why you need the await in there or this to be an async request.

I can however provide a working example of using sendRequest.

pm.sendRequest({
    url: 'https://postman-echo.com/post',
    method: 'POST',
    header: {
        'content-type': 'application/json'
    },
    body: {
        mode: 'raw',
        raw: JSON.stringify([
            { key: "key1", value: 'abcd' },
            { key: "key2", value: '123456789' },
            { key: "key3", value: 1 },
            { key: "key4", value: 'abcd' }
        ])
    }
}, (err, res) => {
    if (err) {
        console.log(err);
    } else {
        pm.test("Status code is 200", function () {
            pm.expect(res).to.have.status(200);
            let resJson = res.json();
            console.log(resJson);
        });
    }
});

I think the bit you are missing is where you set the variables to be used for the error and response as I canā€™t see those options on your sendRequest().

Thank you, Mike. I modified my code based on your response and could get it to work.

I had tried a code similar to the one provided by you and it hadnā€™t worked. In the attempt to fix it, I had started using asynch/await to make sure that pm.sendRequest returned a response before moving on with executing the remainder code.

The reason for my code not working was incorrect usage of curly brackets.

For anyone interested, here is my INCORRECT code:

const tokenEndpoint = pm.environment.get("endPointURL");;
const clientId = pm.environment.get("clientId");
const clientSecret = pm.environment.get("clientSecret");
const credentials = `${clientId}:${clientSecret}`;
const encodedCredentials = btoa(credentials);

// Send POST request to generate a new token
pm.sendRequest({
  url: tokenEndpoint,
  method: "POST",
  header: {
	"Content-Type": "application/x-www-form-urlencoded",
	"Authorization": `Basic ${encodedCredentials}` 
  },
  body: {
	mode: "urlencoded",
	urlencoded: [
	  { key: "grant_type", value: "client_credentials" }
	]
  },
  function (err, res) {
    console.log("Resposnse ", res.json());
    newAccessToken = res.json().access_token;
	if (err) {
	  console.error("Error fetching new token:", err);
	} else {
            if (res.json().code === 200) {
            newAccessToken = res.json().access_token;
            console.log("Successfully retrieved new access token:", newAccessToken);

            // Update the Authorization header for subsequent requests
            pm.environment.set("accessToken", newAccessToken);
		} else {
		  console.error("Failed to fetch new token. Response status:", res.json().code);
		}
	}
  },
});

Here is a full example of sending an authentication request to get a token.

It has embedded tests, and also checks the expiry dates of the token.

Itā€™s just an example, that you might want to consider to make your code more robust.

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

Thank you again, Mike!

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.