Using GCP Cloud Function to create a Python Webhook
Use Case Scenario:
Our use case is to create a Webhook using Python in Google Cloud Platform’s Cloud Run Function. Once the Webhook is deployed, we will send a test data to our webhook in Google Cloud Platform.
Create your Cloud Function
Go to Cloud Function inside Google Cloud Console and click on Create Function
Configuring your Cloud Function
Write the name of the function then select "Allow unauthenticated invocations" in the Trigger and click Next
Setup the Code
In Runtime, select Python 3.11. Delete the initial contents of main.py and requirements.txt.
Create your webhook listener code in main.py
By default your source code will have two files (main.py - contains code and requirements.txt - dependencies)
The "Entry Point" will the name of your main "def" function.
Copy and Paste the code to your main.py in your cloud function
---------------------------
import os
import functions_framework
import json
from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
@app.route('/test', methods=['POST'])
def webhooktest(*args, **kwargs):
jsondata = request.json
data = jsondata.get("payload")
print(data)
return(data)
Copy the contents of requirements.txt below to your requirements.txt in cloud function
Deploying your cloud function
Click on "Deploy" to deploy your cloud function. The cloud function is successfully deployed when you see the green circle with check
Get the generated cloud url
Done. The url generated is your webhook url.
Below is the Python Test Script for sending data to your webhook url
import requests
from requests import request
import json
webhook_url = "https://us-central1-xxx-xxxx.cloudfunctions.net/webhook_test/test"
testdata = {"current": {"url": "https://test.com"}, "payload": {"signup": {"method": "home page", "referrer": "https://auth.wehelpcode.com", "destination": "https://test.com"}, "user": {"id": "4465-a4b4-640a81c5bd75", "first_name": "Code", "last_name": "Gray", "email": "test@test.com"}}}
testresponse = request('POST', webhook_url, json=testdata)
print(testresponse.text)
Related Video:
Watch the explainer video to understand what is a webhook