Send asynchronous requests with Postman’s PM API

The Postman Sandbox is a JavaScript execution environment that is available to you while writing pre-request and test scripts for requests in both Postman and Newman.

pm.* is the new postman.*

You may already know about Postman’s PM API for cleaner and more robust scripting. Building upon the shoulders of the older postman.* API, the pm.* API takes it a step further with more powerful and comprehensive global functions. With the pm.* API, you can do more with scripting, like easily access request and response elements, assert a set of pre-defined rules for testing to enable better and cleaner tests, and manage environments and variables.

Recently, we introduced the pm.sendRequest() function to send requests asynchronously in both the pre-request and test scripts.

What does asynchronous mean?

Related: Understanding asynchronous APIs

JavaScript can be asynchronous, but it is generally single-threaded, meaning it can only process 1 command at a time. If commands are executed asynchronously, subsequent scripts don’t need to be delayed or block any other scripts waiting in line.

If you’re not familiar with the asynchronous nature of JavaScript, let’s take a moment to review.

In the following example, we will use setTimeout(), a native JavaScript function which executes a code snippet after a specified delay in milliseconds. Let’s execute the following code synchronously, and then asynchronously. What do you think will happen?

console.log(“Ping.”);

setTimeout(function() {
 console.log("Pong!");
}, 5000);

console.log(“Where’s the ball?”);

In synchronous code, every command must politely wait for the command before it to complete before it can begin. Synchronous code would execute in the following sequence:

“Ping.”

Wait for 5 seconds

And then, “Pong!”

“Where’s the ball?”

In asynchronous code, setTimeout() schedules something to happen in the future before proceeding to the next line. It doesn’t block the next line of code. Asynchronous code would execute in the following sequence:

“Ping.”

“Where’s the ball?”

Wait for 5 seconds.

And then, “Pong!”

Simply put, with asynchronous scripts, you can now execute logic in the background if you have a heavy computational task or are sending multiple requests. Instead of waiting for a call to complete and blocking any next requests, you can designate a callback function and be notified when the underlying operation has finished.

Send requests asynchronously with sendRequest

Some things to know about pm.sendRequest():

  1. The method accepts a collection SDK compliant request and a callback. The callback receives 2 arguments, an error (if any) and SDK compliant response.
  2. It can be used in the pre-request or the test script.

Here are some examples:

// example with a plain string URL
pm.sendRequest('https://postman-echo.com/get', function (err, res) {
    if (err) {
        console.log(err);
    } else {
        pm.environment.set("variable_key", "new_value");
    }
});

// Example with a full fledged SDK Request
const echoPostRequest = {
  url: 'https://postman-echo.com/post',
  method: 'POST',
  header: 'headername1:value1',
  body: {
    mode: 'raw',
    raw: JSON.stringify({ key: 'this is json' })
  }
};
pm.sendRequest(echoPostRequest, function (err, res) {
  console.log(err ? err : res.json());
});

// example containing a test ** under the Tests tab only
pm.sendRequest('https://postman-echo.com/get', function (err, res) {
  if (err) { console.log(err); }
  pm.test('response should be okay to process', function () {
    pm.expect(err).to.equal(null);
    pm.expect(res).to.have.property('code', 200);
    pm.expect(res).to.have.property('status', 'OK');
  });
});

Using the Postman API can solve a lot of use cases like authentication that may not yet be supported through the Postman app interface. Learn more about the Postman’s powerful PM API and pm.sendRequest() in particular.

Tags:

What do you think about this topic? Tell us in a comment below.

Comment

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.

6 thoughts on “Send asynchronous requests with Postman’s PM API

    If sandRequest is asynchronous, and then using it pre-request scripts means that you can’t use the result in the main request, correct? There is no guarantee that the callback will complete before the main request. If that’s the case, I couldn’t request an auth token and guarantee that the auth token is actually there.

    https://github.com/postmanlabs/postman-app-support/issues/3480

      The main Postman request will not be sent until the pre-request script is determined to be finished with all callbacks, including sendRequest. You should be able to secure an auth token in the pre-request script using sendRequest, and rely on it for the main request.

        Thanks for clearing that up!

    I am trying to send the add Authentication header in headers but it is not going in final call.
    Can anyone help me in this ?

    It is like below :
    const requestStr = {
    method: ‘POST’,
    url: URL,
    headers:
    {
    ‘Authorization’: ‘Basic ‘ ,
    ‘cache-control’: ‘no-cache’,
    ‘Content-Type’: ‘application/x-www-form-urlencoded’
    },
    body:
    {
    mode: ‘urlencoded’,
    urlencoded: [
    {key: ‘key1’, value: ‘value1’},
    {key: ‘key2’, value: ‘value2’},
    {key: ‘key3’, value: ‘value3’},
    {key: ‘key4’, value: ‘value4’},
    ]
    }
    };

    pm.sendRequest(echoPostRequest, function (err, res) {
    console.log(err ? err : res.json());
    });

      In final call Authorization token is not going through….

        If you are still having this issue I’d recommend asking on our community forum: community.postman.com