Trigger collection runs using webhooks

A webhook provides a way to automatically send data from one application to another. Using a webhook, you can trigger a collection run in Postman at a specific time or when an event occurs. You can also send a custom payload to the webhook, which can be accessed when the collection runs. This enables the collection to be run independently of any environment, instead relying on the data sent to the webhook.

Creating a webhook

With a collection webhook, data is sent to the webhook URL using a POST request when certain events are triggered. (It's up to you to configure the application that sends the data and what the trigger events are.) The data sent to the webhook is accessible in the previousRequest global variable that's retrieved using the pm.globals.get method. Using scripts, you can parse that data and use it during the collection run in any way possible.

Webhooks for a collection must be created using the Postman API. To create a webhook, refer to the documentation for api.getpostman.com/webhooks.

Accessing the request body in scripts

When you trigger the webhook, the previousRequest global variable is temporarily created, and its value is the request body of the webhook as a JSON string. Use the pm.globals.get('previousRequest') method to get the request body of the webhook, then parse it using JSON.parse(). The data sent to the webhook is available in the data parameter inside the parsed object, as shown in the following code:

var previousRequest = JSON.parse(pm.globals.get('previousRequest'));

var webhookRequestData = previousRequest.data;

// webhookRequestData contains the data sent to your webhook.
console.log(JSON.stringify(webhookRequestData));

The request body sent to the webhook must use JSON format.

When you create a webhook using the Postman API, a monitor is created for the webhook. You must trigger the webhook in a separate request to run the code in this example using the monitor. Then you can view the monitor run details that were logged to console. For more details about monitor results, see View monitor results.

Sending output to another API

The data that's sent to the collection webhook can be used to define logic and trigger another API. For example, you might set up a webhook for your GitHub repository. Based on the updates happening in your repository, you can use the webhook to run custom build pipelines or perform CI tests.

Last modified: 2023/05/31