Sep 18, 2017

Easy ways to subscribe to a SharePoint List Webhook

Hi guys,

In the beginning of this year, a cool feature was brought to General Availability in SharePoint Online: List Webhooks. They are an alternative to Remote Event Receivers and Flow to trigger process when an event occurs in a list. They are more aligned to the current trends and standards of the Web development industry. It could be quite cumbersome to register a new Webhook, I want to show here multiple easy ways to do so with great tools such as SP Editor Chrome plugin, PnP JS Core and PnP PowerShell.

Subscribe to a new List Webhook

To register (or "Subscribe to") a List Webhook, we need to POST a HTTP message with proper credentials to a particular SharePoint API endpoint. I encourage you to read the Reference Docs to know all the details. Several experts (From Microsoft and the community) built some samples:

On my own, I also built an example with Node.js here at the time of the GA annoucement.

Simpler ways to subscribe to a new List Webhook

While the technique to subscribe to a new Webhook is pretty straightforward, it is also a bit cumbersome because you have to either use a HTTP tool (such as POSTMAN) and get the proper access token, or code an application that will use App Only credentials. I want to show you here multiple easier ways to do it. For each way described in this post, your Webhook endpoint obviously has to be up and running. If you are not sure how to build it, please check the dedicated page in Reference Docs to setup a basic List Webhook hosted in an Azure Function

Use the SP Editor Chrome Extension

This first solution is probably the easiest from a User perspective. It is also the only one that doesn't offer automation possibilities. It consists of using a Google Chrome extension called SP Editor. It is an awesome extension that allows a user to perform many advanced operations on the SharePoint site currently opened in the browser. Once the extension is installed, go to your SharePoint site, press F12 and select the SharePoint tab of the Developer console. speditor.png

  1. Select the Webhooks section
  2. Select the list you want to add a Webhook subscription to
  3. Specify the URL of your Webhook
  4. Click the Add button

Alternatively, with this extension, it is possible to run snippets of code using the PnP JS Core library directly against your site without "installing" it (No need to reference it in the page manually). This library has support for subscribing list webhooks. The SP Editor extension is a great way to test JS code than you can take and embed later in a script editor webpart or a SPFx solution.

  1. Copy/Paste the following snippet into the PnP JS Console.
  2. Set the title of your list as the argument of the getByTitle() method
  3. Change the value of the first argument of the add() method to set your webhook URL.
  4. The second argument of the add() method is the expiration date in ISO string format. It must be maximum 6 months from today.
  5. hit Ctrl+D
import pnp from "pnp";  
pnp.sp.web.lists.getByTitle("testwebhook") 
  .subscriptions 
  .add("https://your-functions.azurewebsites.net/api/sample-webhook", "2017-12-01T00:00:00+00:00") 
  .then(r => console.log("Webhook added")) 
  .catch(r => console.log(r));

speditor-pnpconsole.png

While PnP JS Core library will most likely be used in a Client-Side application (JS embedding or SPFx solution). It can also run in a Node.js application with AppOnly credentials. From an automation perspective, we can imagine implementing gulp tasks that will manage Webhook subscriptions using the PnP JS Core library. These gulp tasks can then be used from CLI or from some ALM pipeline (Check out this excellent post about ALM with SPFx from Elio Struyf).

Use PnP PowerShell Cmdlets

With the PnP PowerShell module installed on your computer (Install-Module SharePointPnPPowerShellOnline, make sure to install at least the September 2017 release), you can use dedicated Cmdlets for managing Webhook subscriptions. You can as well use the provisioning Engine with an external XML template file.

Let's first see how to use the dedicated Cmdlets

Connect-PnPOnline https://yourtenant.sharepoint.com/sites/yoursite 
# "testwebhook" is the name of our target list 
Add-PnPWebhookSubscription -List testwebhook -NotificationUrl https://your-functions.azurewebsites.net/api/sample-webhook  
# The command above outputs the following 
# Id                 : 080e41c2-3c30-4c4d-8d1c-fa22249aedc0 
# ClientState        : 
# ExpirationDateTime : 12-Mar-18 22:00:00 
# NotificationUrl    : https://your-functions.azurewebsites.net/api/sample-webhook 
# Resource           : 6efa3b51-f514-4b88-9117-3d158e3f8fe2  
# We can also remove the subscription with the following Cmdlet 
Remove-PnPWebhookSubscription -List  testwebhook -Identity 080e41c2-3c30-4c4d-8d1c-fa22249aedc0

[^] If your Webhook endpoint is not existing or is not reachable, you most likely will run into the following exception:

> Add-PnPWebhookSubscription : {"odata.error":{"code":"-1, System.InvalidOperationException","message":{"lang":"en-US","value":"Failed to validate the notification URL 'https://your-functions.azurewebsites.net/api/sample-webhook'."}}} 
At line:1 char:1 + Add-PnPWebhookSubscription -List testwebhook -NotificationUrl https:/ ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : WriteError: (:) [Add-PnPWebhookSubscription], Exception + FullyQualifiedErrorId : EXCEPTION,SharePointPnP.PowerShell.Commands.Webhooks.AddWebhookSubscription

When writing this post, I actually encountered an issue I want to share here just to let you know it might happen. My Webhook endpoint was already existing and is hosted in an Azure Function with the cheapest pricing tier. It can go idle, and in that case, it might take more than 5 seconds to respond to the validation request issued by SharePoint. That will result as the error described here above.

Let's see how to use the PnP Provisioning Engine

First you need to have the template to apply. You can extract it from a source site or you can totally build it manually, make sure to have the following template at least for the provisioning engine to be able to process it.

<pnp:Provisioning xmlns:pnp="http://schemas.dev.office.com/PnP/2017/05/ProvisioningSchema">     
  <pnp:Preferences Generator="OfficeDevPnP.Core, Version=2.18.1709.0, Culture=neutral, PublicKeyToken=3751622786b357c2" />     
    <pnp:Templates ID="CONTAINER-TEMPLATE-WEBHOOK">         
      <pnp:ProvisioningTemplate ID="TEMPLATE-WEBHOOK" Version="1" BaseSiteTemplate="STS#0" Scope="RootSite">
        <pnp:Lists>
          <pnp:ListInstance Title="testwebhook" TemplateType="100" Url="Lists/testwebhook">
            <pnp:Webhooks>
              <pnp:Webhook ServerNotificationUrl="https://your-functions.azurewebsites.net/api/sample-webhook" ExpiresInDays="179"/>
            </pnp:Webhooks>
          </pnp:ListInstance>
        </pnp:Lists>
      </pnp:ProvisioningTemplate>
    </pnp:Templates>
  </pnp:Provisioning>

You have to set the values for the attributes of the Webhook element:

  • ServerNotificationUrl: the Url of your webhook endpoint
  • ExpiresInDays: the number of days after which the Webhook will expire. Must be less than 180.

You then have, obviously, to call the cmdlet to apply the template to your site:

Connect-PnPOnline https://yourtenant.sharepoint.com/sites/yoursite $path = ".\The\Path\to\your\template.xml" 
Apply-PnPProvisioningTemplate -Path $path

It is That simple !   While the dedicated Cmdlets could be used in a deployment script with conditions and "dynamic" values, the provisioning engine approach could be really useful when you need to reproduce the configuration of an existing site (or just one list). A combination of both approaches can also be considered.  

As usual, I hope this article will help you with SharePoint list Webhook subscriptions. Feel free to give me your feedback!

Cheers,

Yannick

Other posts