Normally, a "webhook" is a feature of an online service that sends a request to your app at a public url where you have a HTTP server deployed, in response to some event within the service. The url needs to be configured in whatever is sending the request, it's not explicitly set in the receiving code.
The thing that listens to the webhook is an HTTP server with a suitable endpoint defined. To create a server you can use many different packages, but something simple like Flask is a good place to start.
The minimal view code would look something like:
@app.route('/api/bats_hook')
def bats_hook():
data = request.get_json()
print(data)
return 'OK'
If whatever is sending the POST (your nodejs service?) needs to be able to send requests to your server, so you'll either need to deploy the server so it's publicly accessible, or set the service to send the requests to your public IP. If it's on the same machine you can use a private IP, or localhost
.
On the other hand, if a node process is currently receiving the POST requests at https://company/api/bats_hook/
, and you want to notify a python process whenever a job comes in, that's a different problem. You could either send that information on to a separate python server via axios.post
or similar (this might be the easiest option), or store the data somewhere that the python process can access it. Redis would be a good option, because you can easily set up a publish/subscribe system, and the node and python processes can be on the same machine or on different machines. If they're on the same machine, you could also just dump the data to a log file and read that into python. Sending data from one process to another is called inter-process communication, and it gets complicated quickly.
If you were to use redis, with node_redis and redis-py, the implementation might look like:
// javascript
var redis = require("redis"),
redisClient = redis.createClient();
app.post("/api/bats_hook", (req, res, next) => {
console.log(req.query.params)
console.log(req.body)
console.log(req.body.name)
// This publishes a message to the "bats hook channel"
redisClient.publish("bats hook channel", JSON.stringify({
params: req.query.params,
body: req.body,
}));
res.status(200).json({
message: "BATS object",
posts: req.body
});
});
# python
import redis
r = redis.Redis()
p = r.pubsub()
p.subscribe('bats hook channel')
# This blocks and reads any messages from the "bats hook channel" as they come in
for message in p.listen():
print(message)
A lot depends on your intended usage. If the python part is going to be just used for debugging locally, you'd make different choices than if it needs to be deployed.