I have been searching everywhere for tutorials on how to create and implement webhooks which listen for events within a back-end API. For instance, if I had a server written in python flask, how would I listen to server-side events (example: user has created 100 total records) which then executes some more back-end code or requests external data?
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return {"status": 200}
#Some webhook code listening for events in the server
if __name__ == '__main__':
app.run()
What do I write to listen for server events?
You can use flask feature called before_request
it like this
from flask import Flask, jsonify, current_app, request
app = Flask(__name__)
@app.before_request
def hook_request():
Flask.custom_variable = {
"message": "hello world",
"header": request.args.get("param", None)
}
@app.route('/')
def home():
variable = current_app.custom_variable
return jsonify({
"variable": variable,
})
if __name__ == '__main__':
app.run()
and to test it like this
→ curl http://localhost:5000/
{"message":"hello world"}
→ curl http://localhost:5000\?param\=example
{"variable":{"header":"example","message":"hello world"}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With