Skip to navigation

Use scripts to send requests in Postman

View as Markdown

Use the pm.sendRequest method to send a request asynchronously from your scripts. This enables you to run logic in the background if you’re carrying out computation or sending multiple requests at the same time without waiting for each to complete. You can avoid blocking issues by adding a callback function so that your code can respond when Postman receives a response. You can then carry out any more processing you need on the response data.

pm.sendRequest always sends an HTTP request, whatever the type of the request whose script calls it.

The scripts available to you depend on the request type:

  • For HTTP requests, use Pre-request or Post-response scripts.
  • For gRPC requests, use Before invoke, On message, or After response scripts.
  • For GraphQL requests, use Before query or After response scripts.

To send a request in your collection using its request ID, use the pm.execution.runRequest method.

pm.sendRequest

You can pass the pm.sendRequest method a URL string, or you can provide a complete request configuration in JSON including headers, method, body, and more.

For more information, see the Request definition and Response structure reference documentation.

The following examples demonstrate use of the pm.sendRequest method:

Examples

Example with a plain string URL:

try {
const response = await pm.sendRequest('https://postman-echo.com/get');
console.log(response.json());
}
catch (error) {
console.log(error)
}

Example with a full-fledged request:

const postRequest = {
url: 'https://postman-echo.com/post',
method: 'POST',
header: {
'Content-Type': 'application/json',
'X-Foo': 'bar'
},
body: {
mode: 'raw',
raw: JSON.stringify({ key: 'this is json' })
}
};
pm.sendRequest(postRequest, (error, response) => {
console.log(error ? error : response.json());
});

Example containing a test:

pm.sendRequest('https://postman-echo.com/get', (error, response) => {
if (error) {
console.log(error);
}
pm.test('response should be okay to process', () => {
pm.expect(error).to.equal(null);
pm.expect(response).to.have.property('code', 200);
pm.expect(response).to.have.property('status', 'OK');
});
});