Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add webhook events to a flask server?

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?

like image 776
Cody Avatar asked Nov 06 '22 14:11

Cody


1 Answers

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"}}
like image 116
ferdina kusumah Avatar answered Nov 14 '22 22:11

ferdina kusumah