Sending Webhooks with Python

Webhooks

What are Webhooks

Webhooks are a way for applications to communicate with each other. They are becoming increasingly popular in the IT and DevOps fields for generating alerts and events.

The way they operate is simple, when an 'event' happens they send a JSON payload over HTTP to a receiving server. An 'event' can be just about anything, from a device, going offline, a CPU threshold being reached or someone walking into your store and connecting to your WiFi.

It's important to understand how simple webhooks are, and how we can create and receive our own webhooks with Python.

Sending Webhooks

Importing the proper libraries

We will be using the JSON and Requests library for this lab.

import requests
import json

Setting our URL and Data

We will be running a local webhook server, so let's set URL to local loopback.. but you can also use a site like http://webhook.site/ to send your test webhooks to.

url = http://127.0.0.1:5000/webhook

Now let's create a dictionary that we will convert to a JSON payload:

data = { 'name': 'DevOps Journey', 
         'Channel URL': 'https://www.youtube.com/channel/UC4Snw5yrSDMXys31I18U3gg' }

Setting up the Webhook request

r = requests.post(webhook_url, data=json.dumps(data), headers={'Content-Type': 'application/json'})

Sending the Webhook with Python

Put this code into you webhook.py script and then run it. Make sure to set the URL to your webhook server and customize the data payload.

 Terminal
python webhook.py

Voila! You have sent a Webhook!

Check out Part 2 of this lesson to see how to a python script to Receive the webhook!