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! πŸ‘¨β€πŸ’»πŸ”₯

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly β€” using the tools and languages you already love!

Learn More

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay