A webhook is a type of service that allows one program to send data to another as soon as a particular event takes place. Webhooks are useful in cases where a specific code needs to be executed when an event occurs. For example, we can set a webhook to trigger an endpoint when confirming purchase order, creating a new product, sell a product through pos, etc. so, instead of having to check each minute to see if there is a new event happening or not, we can tell the app that this event has occurred in using webhooks. In this tutorial, we’ll create a program to receive Github webhooks in Python.
Why Choose Flask For Creating Webhooks
The Flask web framework is a great way to start developing an application because it is relatively easy to get started, but it is also easy to get stuck in if you do not know what you are doing. Flask is a web framework that helps us to easily create web applications. We will cover most of the basics and talk about how to write a quick demo app to test our setup. Also, this post is meant to be a little advanced, so you should be familiar with the basics of Flask. Before we start coding, we have to understand how a webhook works. Overview of a webhook At its most basic, a webhook is just a URL. So, a webhook is just a URL pointing to some endpoint. The endpoint is normally a directory but can be a URL, console, or other application. The endpoint can be started by the server or it can be done manually. The Flask makes it very easy to receive github webhooks in python.
Installing the Prerequisites
To get this application up and running, make sure that you have done the following:
- Download and install Python
- Download and configure pip
- Install Flask
Setup a Virtual Environment
An environment like Virtualenv is an option to keep our development environments separate, but we need to install the pip package manager to set up our environment. Using pip would require you to have Python 2.7 installed.
To install pip, open up a terminal and run the following command:
pip3 install virtualenv
You can check the version of virtual env using this command:
To create a new virtual environment go to your application directory and run tr following command:
python3 -m venv --system-site-packages .\env
Activate your environment by:
Now, to set up your webhook, your application must be online. Being online is the only way that your application and the webhook provider can communicate with each other. To overcome this obstacle, you can install this piece of software called Ngrok. It is free software that helps expose your local server to the world by setting up port forwarding.
To install Ngrok go to their official download page or run the following command:
pip3 install ngrok pip3 install flask
Creating the Application
For this tutorial, we’ll just be creating a simple single-page application. Create an application file called webhook_test.py (you can name this anything you want).
from flask import Flask #importing Flask to make everything work app = Flask(__name__) @app.route('/') def root(): # function return 'Hello World!' if __name__ == '__main__': app.run(debug=True)
To check if everything works, run this application in the terminal where your application file is located:
If that worked successfully, you should see a response like this:
[email protected]:~/Desktop/Flask_Tutorial$ python3 webhooks_test.py * Serving Flask app 'webhooks_test' (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 750-408-886
Now to see your application running, open this “
http://127.0.0.1:5000/” link in a browser.
Creating the Webhook
For this tutorial, we are going to be using webhooks from Github, as it is very simple to understand and work with. Now, in order to receive information through Github, we’ll have to make a method that will do just that. And to do that edit your application file like so:
from flask import Flask from flask import request from flask import json #importing json cause that’s what we’re going to be working with app = Flask(__name__) @app.route('/') def root(): return 'Hello World!' @app. route('/hooktest', methods=['POST']) # ‘/hooktest’ specifies which link will it work on def hook_root(): if request.headers['Content-Types'] == 'application/json': # calling json objects return json.dumps(request.json) if __name__ == '__main__': app.run(debug=True)
That’s it! Now if you run it and go to “
http://127.0.0.1:5000/hooktest”, you will see an error stating “Methods Not Allowed” but that’s fine, we don’t have to care for it.
Putting Your Application Online
Now, in order for your application to connect to Github, you will have to put it online; and that’s why we installed Ngrok. To use it, run the following command in your terminal where your application is located and run the following command:
Note: make sure your local server is running before running this command.
Ngrok http 5000 # 5000 is your port number
After that you would see a response something like this:
ngrok by @inconshreveable (Ctrl+C to quit) Session Status online Session Expires 1 hour, 57 minutes Version 2.3.40 Region United States (us) Web Interface http://127.0.0.1:4040 Forwarding http://6f50-106-77-191-55.ngrok.io -> http://localhost:5000 Forwarding https://6f50-106-77-191-55.ngrok.io -> http://localhost:5000 Connections ttl opn rt1 rt5 p50 p90 0 0 0.00 0.00 0.00 0.00
This means that your local server is now online! To see this in action, visit the provided link, which is
https://6f50-106-77-191-55.ngrok.io this is my case.
Connecting to Github
Follow these steps to get a webhook Github:
- Make your own repository and open it.
- Go to the settings of your repository.
- Open the “Webhooks” Section and then click on the “Add Webhooks” button.
- In the “Payload URL” section, enter the URL generated by Ngrok.
- Select “application/json” on the “Content type” dropdown.
- Leave the “Secret” section empty.
- In the “Which events would you like to trigger this webhook?” section, select anything you want but for simplicity sake we’ll select “Let me select individual events.” and select only “Issues”.
- Lastly press the “Update webhook” button.
Now, If you will post an issue and the repository you will get a hit on your terminal; the response would be something like so:
127.0.0.1 - - [29/Sep/2021 15:35:22] "POST /github HTTP/1.1" 200 -
Writing webhooks does not have to be a difficult task. There are many improvements that can be made in this regard and it is advised that you seek further advice in relation to this subject matter.
The article above has discussed how to configure a basic Flask webhook. We went over the basic concepts to use a Flask webhook, including publishing events to the server, defining an event handler, and using the events keyword. If you have questions or comments about Flask webhooks, you are more than welcome to leave them below. I hope you were able to make the program work and were able to receive Github webhooks in Python.
Here are some useful tutorials that you can read:
- How to convert an image to 8-bit image
- How to create a web app using Pyramid framework
- Create various charts using Python
- Password generator using Python and Secrets
- Create API in Django Rest Framework Viewset
- Create Sudoku game in Python using Pygame