Wednesday, 7 March 2018

Working with SharePoint Events using Webhooks

Introduction


In this post, let us look in detail on webhooks functionality. At a high level, there are two independent steps to work with Webhooks.
  • Subscribing to the SharePoint events (remote events)
  • Processing Events.
Note: In the recent SharePoint Saturday Event at Chennai, I have explored on using Serverless Webhooks. For the benefits of larger audience, I am writing down as a technical post in detail with explanations.

Subscribing to the SharePoint Events


SharePoint by default provides the subscription mechanism for event changes. For now, only item level changes can be tracked, that on SharePoint online platform.

The services can be hooked to the item events on SharePoint, by making post calls to the respective lists. In this case, you need to create independent service. Once created, the following steps needs to be executed.
  • You need to register the webhooks service using the SharePoint list subscription REST API post call. 
    • This can be done by making POST request to the respective list. The Post URL will look like /_api/web/lists('list-id')/subscriptions
    • The data that needs to be passed is shown below.
  • Upon receiving the request, SharePoint service will fire post call with the validation token to the webhook service built. The service URL will look like https://{your host}/your/webhook/service ?validationToken={randomString}.
  • Once webhook service receives the request, it should have the capability of responding back with token sent.
  • If the above flow happens within 5 seconds of time, SharePoint service will respond back to the user request saying webhook service subscription details. If it exceeds more than 5 seconds, the registration will fail. 

The below snapshot shows the detailed flow diagram on how the subscription happens.

Subscribing to the SharePoint Events
Subscribing to the SharePoint Events


Processing Events


  • Whenever there is a change in the items from the subscribed list, SharePoint will push the data into the subscribed webhook service. The post data will contain the necessary change details like, (Data is shown in the architecture below) 
    • subscription id, 
    • expiration date of subscription, 
    • resource (list id), 
    • tenant and web id. 
  • Once webhook receives any request, it needs to save it somewhere for processing. The Azure storage queues are the easiest ways to push the data.
  • Once pushed to the queue, the webhook service will respond back to the SharePoint service posting success message.

The following snapshot shows the events flow.

Processing Events
Processing Events

Next, let us look how to process the events stored on storage queues with the samples.