3 minutes read

So you are building your own bot and now you want to add your business logic. This logic might come from one of your REST APIs or databases. Now how do you call this API in Botpress? In this post, we will see 2 ways to call an API in Botpress, using the Call API provided by Botpress and custom actions. In the below screenshot [1] node is using Botpress Call API and [2] is using custom action to call our API. Let’s get started.

How to call an API in Botpress?
Call an API in Botpress

Botpress Call API skill usage

Botpress provides a Call API skill by default. In the below screenshot we see a bot studio, we will follow the below steps to configure a Call API.

  1. Click on the symbol pointed by [1] marker, it will create a node [2].

2. Rename this node as N_CallAPI or anything that you can recognize later.

3. Click on this node and then click “Edit skill” button [10].

4. This will open a popup as shown below [3].

5. Here you can provide the request method [4], request URL to your API [5].

6. Since this is a POST call, I am going to provide a request body [6] that is required by my REST API.

{
    "user": "{{event.payload.text}}",
    "type": "latest_posts"
}

Note: Here the REST API residing at localhost:5000/aabingunz/api/v1/postlist accepts and provides data in JSON format.

Call api
Botpress Call API

7. It’s best to use JSON when working with Botpress and API calls. This is why under the Headers section [7] we will provide content-type and accept as “application/json” type.

{
  "Content-Type": "application/json",
  "Accept": "application/json"
}
Call api headers section
Botpress Call API Headers section

8. Under the Memory section, we will save the response using any of the memory variables. Here I am saving the response in the Session memory variable.

Call api memory section
Botpress Call API Memory section

9. We will configure success and failure transition nodes. Here I have selected an always condition for transition on success or failure.

call api node properties

Note: Once a response is received and if the status code is anything above 400, it will be treated as a failure, and the flow transitions to the failure flow.

10. At the end we will use a custom action to check and process response data. Please check the custom action section for an explanation.

/**
   * A custom action to process the API response
   * Here the API returns below response
   * {"user":"Abhishek","message":"Latest posts on Aabingunz.com, subscribed by Abhishek","data":[{"title":"How to write clean code all the time?"},{"title":"The Essential Chatbot Terminology"},{"title":"How to use values from the database in Botpress?"},{"title":"Botpress tutorial – How to create actions?"}]}
   * @title A custom action to process the API response
   * @category Utility
   * @author Abhishek Raj Simon
   */
  const myAction = async () => {
    bp.logger.debug(`${JSON.stringify(session.response.body)}`)
    let data = session.response.body
    for (let obj of data.data) {
      let payloads = await bp.cms.renderElement('builtin_text', { text: obj.title }, event)
      await bp.events.replyToEvent(event, payloads)
    }
  }

  return myAction()

This is how you can use the already existing Botpress Call API skill.

Botpress Custom Action to call an API

Let’s check an alternate way, where you would like to programmatically call the API in your custom action You can view this tutorial to understand Botpress custom actions and how to create one.

For this tutorial, I have created a custom action that does the same job as the Call API skill.

  /**
   * A custom action to call REST APIs
   * @title The title displayed in the flow editor
   * @category Custom
   * @author Abhishek Raj Simon
   */
  const myAction = async () => {
    var axios = require('axios')
    // You can use event.payload.text to get users input
    var data = JSON.stringify({
      user: event.payload.text,
      type: 'latest_posts'
    })

    var config = {
      method: 'post',
      url: 'http://localhost:5000/aabingunz/api/v1/postlist',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      data: data
    }
    let response = await axios(config)
    for (let obj of response.data.data) {
      let payloads = await bp.cms.renderElement('builtin_text', { text: obj.title }, event)
      await bp.events.replyToEvent(event, payloads)
    }
  }

  return myAction()

The above custom action is sending the POST body params defined in the data variable and required headers. We are using Axios library to make a rest call, which is available by default in Botpress. Once the data is fetched we get the below response from our API (same as Call API).

{
    "user": "aabingunz",
    "message": "Latest posts on Aabingunz.com, subscribed by aabingunz",
    "data": [
        {
            "title": "How to write clean code all the time?"
        },
        {
            "title": "The Essential Chatbot Terminology"
        },
        {
            "title": "How to use values from the database in Botpress?"
        },
        {
            "title": "Botpress tutorial – How to create actions?"
        }
    ]
}

In the above response, we are interested in the data part which is a JSON array. We will iterate over this array and try to respond with all the latest post titles in our bot. To make our bot reply programmatically we will use the Botpress SDK method and use builtin_text content type.

let payloads = await bp.cms.renderElement('builtin_text', { text: obj.title }, event)
await bp.events.replyToEvent(event, payloads)

This is how we can use to call an API in Botpress. Hope this tutorial is helpful, you can download the bot export from here.


Simon

I am a Fullstack developer and Consultant with an experience of 9+ years in the industry. I mainly work on Java, React, Javascript, NodeJs, Elasticsearch and Botpress.

0 Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.