Dialogflow Fulfillment: Webhook Tutorial Using Python (Flask)

Chatbots, Python Development, Machine Learning, Natural Language Processing (NLP)

Dialogflow is a chatbot building framework that helps you build and deploy your own chatbots to multiple platforms like Google Assistant, Facebook Messenger, Telegram, Twitter, Slack, Line, Viber and many others. It is powered by a Machine Learning based NLU (Natural Language Understanding). The feature rich Dialogflow lets you create chatbot with ease.

In this blog, we are going to take a look into one pretty useful feature of Dialogflow: Fulfillment. Using Fulfillment you can communicate with your server/database to generate dynamic responses. In Fulfillment, we develop a webhook on our server which accepts request from Dialogflow, process the request and respond with Dialogflow compatible JSON.

Let’s dig deeper into webhook to understand how it works and what are the benefits a chatbot developer can leverage using it.

What is webhook?

A webhook is a user defined HTTP callback that is automatically invoked whenever certain criteria is fulfilled. A webhook can be created in any server side programming language like Python, PHP or Node.js. You can read more about webhook here.

In Dialogflow, a webhook can be used to fetch data from your server whenever a certain intent having webhook enabled (don’t worry, we will see that) is invoked. The information from the intent is passed to the webhook service to receive result.

We are going to use Ngrok, (a web tunneling tool) that can be used to call webhook from your local server. You can download Ngrok from ngrok.io.

Let’s start building our own Dialogflow agent with webhook using Python (Flask) and deploy it using Ngrok.

Install Python

Download and install python from here as per your supported OS.

Install Flask using PIP

Flask is a lightweight web framework that can be used to create webhook service which can communicate with external application (in our case Dialogflow’s agent). To use flask in our app, first we need to install it. It can be easily installed using “pip”. If “pip” is not installed then you will need to install it first.

pip install Flask

For more information you can visit: https://pypi.org/project/Flask

Creating webhook using Python

Let’s create a basic flask app.

# import flask dependencies
from flask import Flask

# initialize the flask app
app = Flask(__name__)

# default route
def index():
    return 'Hello World!'

# create a route for webhook
def hello():
    return 'Hello World!'

# run the app
if __name__ == '__main__':

Now, run the app using the following command.

python app.py or FLASK_APP=hello.py flask run

Our basic app is working now, but as it is on local system it can not be accessed from outside world. To integrate it as webhook for Dialogflow, we need to make it live/online. For that, we use ngrok.

Run the webhook using Ngrok

Ngrok is a web tunnelling tool that provides a way to test APIs and webhooks from local server. There are two versions available. I am using the free version with registration on ngrok.io.

To run ngrok, use the following command: ngrok http <port_number>
e.g. ngrok http 5000 (for flask app)

How to setup webhook in Dialogflow

Dialogflow provides an option on the left sidebar known as Fulfillment. Just enter your webhook url generated by ngrok and your are done.

Enabling webhook for intents

Now, we need to enable the webhook for intents that needs to communicate with our server data. To do that, open the intent for which you want to enable webhook, scroll down to the end and enable the “Enable webhook call for this intent” switch.

Whenever this intent is invoked, it will send request to your webhook and respond as per the response set from the webhook.

Setup training phrases for the intent

Training phrases are the sentences that helps the agent to identify/invoke the particular intent.

Setup parameters and action for the intent

We have to set up “Actions and Parameters” in the intent which can be used on our webhook to process the request.

In our example, we have setup “get_results” as “Action”. So whenever this intent will call our webhook, in POST request, we’ll get “get_results” as “action”. If there are multiple intents invoking webhook then we can use “action” to differentiate them and based upon that generate different responses.

We can also pass “Parameters” to our webhook. To do that, we can define Parameter name and its value.

Both Actions and Parameters are optional values so webhook call will work even if you don’t pass them. To differentiate intents without action, you can simply check the intent name in the request JSON.

Building fulfillment responses from webhook

Webhook responses should be in a proper JSON format so that Dialogflow can understand what to display to the user.

You can refer various JSON formats for webhook on this github page.

We are going to build some responses in python using this formats. Types of responses available are: Simple Response, Basic Card, Suggestions, List Card, Browse Carousel, Carousel Response. We will be building all these responses in the upcoming blog.

Below code will prepare a simple JSON response with fulfillment text for Dialogflow. The user will receive “This is a response from webhook.” as response for this intent.

# function for responses
def results():
    # build a request object
    req = request.get_json(force=True)

    # fetch action from json
    action = req.get('queryResult').get('action')

    # return a fulfillment response
    return {'fulfillmentText': 'This is a response from webhook.'}

# create a route for webhook
@app.route('/webhook', methods=['GET', 'POST'])
def webhook():
    # return response
    return make_response(jsonify(results()))

You can see that we have fetched “action” from the request using

action = req.get('queryResult').get('action')

In our example, we haven’t used action, but if you want you can use it for your purpose.

Checking response from webhook

Using console on right side of the window, we can invoke the intent and check the response. For our example, the response will be as below:

Clicking on “DIAGNOSTIC INFO” button, we can view the all detail about request being sent from Dialogflow and response being sent from our webhook. “DIAGNOSTIC INFO” can also be very useful for debugging, if you have any error in your webhook.

Using this tutorial you can create a basic webhook. If you want to enhance your webhook or make it more powerful then Python Library we created to simplify building the JSON responses for Dialogflow can be pretty useful.

Hope this tutorial will be helpful to you in integrating webhook in your dialogflow app. If you have any question then post it in the comment. We’ll respond to it soon.

Feel free to contact us or email at letstalk@pragnakalp.com for your chatbot development requirement. We would love to cater to your development needs at competitive rates with utmost quality and highest customer satisfaction.

4 Responses

  1. Rishabh says:

    How can we make our bot memorise information which was talked over in past. So that next time when user comes online, my bot says about things which were talked last time.
    For example, How was your experience last time.
    How was your shopping yesterday.
    Something like that ?
    Do we need to build our DB for that ? And bot can look up DB what was talked over last time ?

  2. Mohammed Balfakeih says:

    I am performing everything as said in the tutorial, but I am receiving Error 405 Method not allowed.

    • Hello Mohammed,
      Can you please confirm that for /webhook path you are declaring methods properly like below?

      @app.route(‘/webhook’, methods=[‘GET’, ‘POST’])

      If this doesn’t fix your issue then share your webhook file code so that we can help you further.

Leave a Reply

Your email address will not be published. Required fields are marked *