DEV Community

SebasQuiroga
SebasQuiroga

Posted on

2 1 1 1

Creating a Webhook in ServiceNow: A Step-by-Step Guide 🔥

Introduction

🌐 Webhooks are a powerful way to enable real-time integrations between ServiceNow and external systems. 🔄 Whether you're sending incident updates 🆘 or triggering external workflows ⚙️, webhooks help streamline automation 🤖.

In this guide, we'll walk through setting up a webhook in ServiceNow step by step 🛠️, covering everything from writing the script ✍️ to configuring the event registry 📜 and business rule 📌.

By the end, you'll have a fully functional webhook ✅ and the debugging skills 🕵️‍♂️ to troubleshoot issues effectively. 🚀

🔥 TL;DR

Whenever a new operation (Create 🆕 / Update ✏️ / Delete ❌ / Query 🔍) is performed on the Incidents table, we’ll:

1️⃣ Create a Business Rule 📌 that executes after the operation finishes (to grab the most up-to-date data).

2️⃣ Dispatch an Event 🚀 with two parameters:

  • Current Data 📦 (which is needed in theory but doesn't work well for extracting data).
  • sys_id 🆔 (a unique identifier for each record).

3️⃣ Write an Event Script 💻 that:

  • Uses sys_id to query the Incidents table.
  • Fetches the latest data 📅.
  • Sends it to an external consumer 🌍.

By the end, we’ll have a real-time data synchronization ⚡ and a fully functional webhook for external integrations! 🔗🚀

1️⃣ Registering the Event in the Event Registry

We need first create an event.

Steps:

  1. Navigate to Plataform Analytics Administration > Data Collector > Event Registry.
  2. Click New to create a new event.
  3. Set Table to Incident [incident].
  4. Add a description like Triggers a webhook when an incident is created or updated.
  5. Click Submit to save the event.

2️⃣ Creating the Script Action to Send an HTTP Request

The core of our webhook is a Script Action, which will send an outbound HTTP request when triggered. Let's start by writing the script that will handle this operation.

Steps:

  1. Navigate to System Policy > Events > Script Actions.
  2. Click New to create a new script.
  3. Set the Event name to match the one we'll register in the step above (e.g., incident.webhook).
  4. Check the Active checkbox
  5. Use the following script to send an HTTP request:
(function executeWebhook(event) {
    try {

        const consumerEndpoint = "https://YOUR_ENDPOINT";

        gs.info("🔥 Outbound Message");

        const sysId = event.parm1;

        var incidentTableRecord = new GlideRecord("incident");

        incidentTableRecord.get(sysId);

        incidentTableRecord.query();

        if (incidentTableRecord.next()) {

            const recordSysId = incidentTableRecord.getValue("sys_id");
            const shortDescription = incidentTableRecord.getValue("short_description");
            const description = incidentTableRecord.getValue("description")
            const date = incidentTableRecord.getValue("sys_created_on");
            const state = incidentTableRecord.getValue("state");
            const incidentId = incidentTableRecord.getValue("number")
            const priority = incidentTableRecord.getValue("priority");

            var requestBody = {
                shortDescription,
                recordSysId,
                date,
                state,
                incidentId,
                description,
                priority
            };

            gs.info("Sending Webhook Payload: " + JSON.stringify(requestBody));

            var restMessage = new sn_ws.RESTMessageV2();

            restMessage.setEndpoint(consumerEndpoint);
            restMessage.setHttpMethod('POST');
            restMessage.setRequestHeader('Content-Type', 'application/json');
            restMessage.setRequestBody(JSON.stringify(requestBody));

            var response = restMessage.execute();

            var responseBody = response.getBody();

            gs.info('✅ Webhook response: ' + responseBody);


        } else {
            gs.info("❌ No incidents found.");
        }

    } catch (error) {
        gs.error('Error sending webhook: ' + error.message);
    }

})(event);
Enter fullscreen mode Exit fullscreen mode
  1. Click Submit to save the Script Action.

3️⃣ Creating a Business Rule to Trigger the Webhook

With the event in place, we need a Business Rule to fire it when an incident is created or updated.

Steps:

  1. Navigate to Activity Subscriptions > Adminsitration > Business Rules.
  2. Click New.
  3. Set Table to Incident.
  4. Set When to After
  5. Check Insert and Update checkboxes
  6. In the Advanced section, add the following script, updating it the event name created.
(function executeRule(current, previous /*null when async*/) {
    gs.info("Executing Business Rule");
    gs.eventQueue("your.event.here", current, current.sys_id); // UPDATE YOUR EVENT HERE
})(current, previous);
Enter fullscreen mode Exit fullscreen mode
  1. Click Submit to save the Business Rule.

4️⃣ Time to create an incident 😏

Use REST API Explorer

Debugging and Troubleshooting

  • Check the System Logs 🔥

If your webhook isn't working, go to System Logs > All and search for:

  • Verify the Event is Triggering

  • Use REST API Explorer

Conclusion 🎉

By following these steps, you've successfully created a webhook in ServiceNow using a Business Rule, Event Registry, and Script Action. This setup enables real-time integration with external services and can be customized further based on your needs. 🚀

Let me know if you have any questions or need enhancements! Happy coding! 👨‍💻🔥

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay