Processing webhooks on your server
After you have added your webhooks, you can process Inkit events from them on your server. We will send you a signature in the header of the request called Inkit-Signature
that you should compare with a signature generated from your webhook secret key. We will also send you the following object in the request body:
Property | Type | Description |
---|---|---|
event_type | String | The webhook event code. |
resource_id | String | The ID of the resource associated with the request. |
For example:
{
"event_type": "DOCUMENT_CREATE_FINISHED",
"resource_id": "doc_2N0X2g4f3b1JJU75fqzDZs"
}
There are many ways you can process webhooks, but in the following example we'll create a webhook listener in Python using the Flask web framework. It will listen for the Document Created event and will print out data about each document generated in Inkit.
Note: The sample code makes use of the webhook secret key to make sure that the callback came from Inkit. You can get the webhook secret key by editing the webhook.
# Import the Inkit Python library
import inkit
from inkit.exceptions import InkitResponseException
# Import Flask (https://flask.palletsprojects.com/en/2.3.x/)
from flask import Flask, request, abort
# Import HMAC cryptography library
import hmac
# Import SHA-2 hash library
from hashlib import sha256
# Import JSON library
import json
# Replace the string below with your API key
inkit.api_token = "ENTER YOUR API KEY"
# Replace the string below with your webhook secret key
secret = "ENTER YOUR WEBHOOK SECRET KEY"
app = Flask(__name__)
# Set the webhook server path and associate method with route
@app.route('/webhook', methods=['POST'])
def get_webhook():
if request.method == 'POST':
# Check if signature generated from secret key matches header signature
header_signature = request.headers.get('Inkit-Signature')
secret_signature = hmac.new(key = secret.encode('utf-8'),
msg = request.get_data(),
digestmod = sha256
).hexdigest()
# Return a 401 error if the signatures don't match
if header_signature != secret_signature:
print('Invalid signature!')
abort(401)
# Get the webhook object
data = request.json
# Process webhook based on the event type
match data['event_type']:
case 'DOCUMENT_CREATE_FINISHED':
# Get data about the generated document
resp = inkit.Document.get(data['resource_id'])
# Print the data
print(json.dumps(resp.data, indent = 3))
return 'success', 200
else:
abort(400)
# Run the webhook listener
if __name__ == '__main__':
app.run()
To run this code on your web server, save it as webhook.py
and then execute python webhook.py
in your terminal or command prompt.
Note: The above code requires Python 3.10 or greater and processes events at the
/webhook
path of the server. To change this to a different path, edit the@app.route()
method call.
Updated 11 months ago