DEV Community

alokkumarsbg
alokkumarsbg

Posted on

WebHook or Reverse API

I do some Development work as a freelancer to keep updated myself with new kinds of work apart from being a Support Engineer.

I came up with work where I was to write a code where data is to be exposed as a JSON. I thought its easy work can be done quickly. But there was a tweak on the work. The code was to send as JSON to Webhook not exposed as an API. First time I came up with the word Webhook. I checked for an hour with my teacher GOOGLE. I really liked the concept of Webhook which I like to share with all of you.

WebHook or also said Reverse API is a concept where data in any format is sent to the other application POST method URL. Normally in API, we keep checking with the server for any new data in the API. But in Webhook, the server when to find any changes in data is sent to the client application.

This prevents a lot of traffic onto the server, as the client doesn't have to make requests every time to check for updated data. But API has its own use.

Now let's understand it through code perspective.
First, let me make a Post Method in FLask Server that accepts a JSON file. This method will accept the code. So this will be webhook URL(http://localhost/webhook)

@app.route("/webhook",methods=['POST'])
def respond():
    print(request.json)
    return Response(status=200)
Enter fullscreen mode Exit fullscreen mode

The server end will now send the data to this URL when it's triggered using some condition. When the triggered condition is met the data will be sent to the URL.


# WebURL which will accept this Json file
webhook_url = "http://localhost/webhook"

# DB connection
cnxn = db_conn()

# SQL Query. Place your own query
df = pd.read_sql_query('''select * from sample''',cnxn)

# Convert sql result in json format
json_response = df.to_json(orient='records')
print(json)

# Send data to URL
while True:
if triggered: #Any condition as per your design logic
    reponse = requests.post(
    webhook_url,data=json.dumps(json_response),
    headers = {'Content-Type': 'application/json'}
)

# Raise Error if data send not successfull 200 code for successfull
if reponse.status_code != 200:
    print(reponse.status_code)
    raise ValueError("Error")
Enter fullscreen mode Exit fullscreen mode

This Youtube link explains more about WebHook which is used in Github. Do watch this.

Top comments (0)