Code-based Actions: Retrieve data from a database
You can integrate your bot with a database to retrieve data and use the data in conversations within the bot. Use the following steps:
- Extract data or user input
- Retrieve data (GET)
- Personalize the experience
In addition to retrieving data from a database, it is also possible to push data to a database (POST). Read more about how to integrate your chatbot with a database.
Extracting data and user input
Extraction of the data can be done by capturing user input and by using the payload. Read more about it in working with databases.
In this example, we will use the phone number of the user that we receive by the payload as the user interaction via WhatsApp
Retrieve data (GET)
Let's use a database from Restdb to retrieve the data. Setting up and filling the database is part of a previous step, as described in working with databases. At this stage, the database contains only one record.
We are API calls to retrieve data from the RestDB database. If you are using RestDB you can access developers mode by clicking the gear/settings icon in the top right. Access API docs> Javascript. Copy and paste the GET code from RestDB to action in Flow.
The next step is to alter the code in Flow Action so that we can retrieve only relevant data. In this case, data is retrieved using the user name. To increase security, you could also use the phone number, date of birth, or a combination.
async payload => {
var fullName = ""
// Check if name exists
if("fullName" in payload.user.profile) {
fullName = payload.user.profile.fullName
}
const options = {
method: 'GET',
url: `https://integratedb-74ce.restdb.io/rest/userdata?q={"name": "${fullName}"}`,
headers: {
'cache-control': 'no-cache',
'x-apikey': 'YOUR SECRET API KEY'
}
};
let result
try {
const { data } = await request(options)
result = data
} catch (err) {
console.error(err)
throw err
}
const { name, email } = result[0]
// notice API may return more then 1 item in the array
return new Message(`Hi ${name}, is ${email} still your email address?`)
}
Personalize the experience
We now have more data that is related to this specific person. For example, we can send him a confirmation email. The get request will return information in code. That means that we need code to display our message to the user.
Updated 11 months ago