---
title: "How to Integrate Brainfish API with WhatsApp for Automatic Responses"
description: "Overview"
canonical_url: "https://help.brainfi.sh/articles/how-to-integrate-brainfish-api-with-whatsapp-for-automatic-responses-9uNhT7kEtp"
md_url: "https://help.brainfi.sh/articles/how-to-integrate-brainfish-api-with-whatsapp-for-automatic-responses-9uNhT7kEtp.md"
---
# How to Integrate Brainfish API with WhatsApp for Automatic Responses

## Overview

Use the WhatsApp Business API and Brainfish API together to automatically respond to incoming WhatsApp messages with context-sensitive answers.

## When to Use This Guide

* Use this guide if you want **business automation**: customers message a WhatsApp Business number and a server replies using Brainfish.
* If the goal is setting up a **personal WhatsApp account**, this guide does **not** apply (install the WhatsApp app and verify a phone number instead).

## High-Level Setup (Quick Summary)


1. Set up a small web service environment (example uses **Node.js**) and install dependencies (e.g., `express`, `axios`).
2. Generate a **Brainfish API token**.
3. Set up **WhatsApp Business API** in Meta (Business account, phone number, templates as needed).
4. Create a webhook server that:
   * Receives inbound WhatsApp webhook events
   * Extracts the user message
   * Calls the Brainfish API
   * Sends Brainfish’s response back via the WhatsApp Business API
5. Configure the webhook callback URL in the Meta Developer Dashboard and complete webhook verification.
6. Test end-to-end by messaging the WhatsApp number.


---

This guide will teach you to create a system that automatically responds to WhatsApp messages using the Brainfish API. We’ll cover setting up a server, configuring WhatsApp Business API, and writing code to bridge Brainfish and WhatsApp.


---

## **Prerequisites**

* **Brainfish API Access**: You’ll need an API token from Brainfish.
* **WhatsApp Business API Account**: Set up via Meta for business use cases.
* **Node.js & npm**: Install these to run a server.


---

# **Step 1: Setting Up Your Development Environment**


1. **Install Node.js**: Download and install [Node.js](https://nodejs.org/), which includes npm (Node Package Manager).
2. **Set Up a New Project**:
   * Open a terminal.
   * Create a project directory and initialize it with npm:

     ```javascript
     bash
     ```

     Copy code

     ```javascript
     mkdir whatsapp-brainfish-integration
     cd whatsapp-brainfish-integration
     npm init -y
     
     ```
3. **Install Required Packages**:
   * We’ll use express for handling HTTP requests and axios for making API calls.

     ```javascript
     bash
     ```

     Copy code

     ```javascript
     npm install express axios
     
     ```


---

# **Step 2: Generate a Brainfish API Token**


1. Go to **Brainfish Settings → Advanced → API Tokens**: [Brainfish API Token Page](https://app.brainfi.sh/settings/tokens).
2. Click **"Create New Token"**, name it (e.g., "WhatsApp Integration"), and **copy the token**.

⚠️ **Important**: Keep this token safe—it should be used only on secure servers.


---

# **Step 3: Set Up WhatsApp Business API**

To send automated messages on WhatsApp, you need a WhatsApp Business API account.


1. **Sign up on Meta for WhatsApp Business API**: Visit [WhatsApp Business API Getting Started](https://developers.facebook.com/docs/whatsapp/getting-started).
2. **Get a Phone Number and Approve Message Templates**:
   * Register a phone number dedicated to your WhatsApp API.
   * Submit and approve message templates (e.g., "Hello! Thank you for reaching out. We'll get back shortly.").
3. **Set Up Webhook**:
   * In your Meta Developer Dashboard, under **Webhooks**, configure the webhook URL (we’ll create it next) where incoming messages will be sent.


---

# **Step 4: Create the Server to Handle WhatsApp and Brainfish API Calls**

Let’s create an Express server to handle incoming WhatsApp messages and make requests to the Brainfish API.


1. **Create a new file** server.js in your project directory.
2. **Paste the following code**:

   ```javascript
   javascript
   ```

   Copy code

   ```javascript
   const express = require('express');
   const axios = require('axios');
   const app = express();
   
   app.use(express.json());
   
   // Step 4.1: Webhook endpoint for WhatsApp
   app.post('/webhook', async (req, res) => {
     try {
       // Step 4.2: Extract incoming message and sender details
       const incomingMessage = req.body.text;
       const senderPhone = req.body.from;
   
       // Step 4.3: Query Brainfish API with incoming message
       const brainfishResponse = await axios.post(
         'https://app.brainfi.sh/api/articles.contextual.search',
         { query: incomingMessage },
         {
           headers: {
             'Authorization': 'Bearer YOUR_BRAINFISH_ACCESS_TOKEN',
             'Content-Type': 'application/json',
             'Accept': 'application/json'
           }
         }
       );
   
       const answerText = brainfishResponse.data.data.suggestedAnswerText;
   
       // Step 4.4: Send response back to WhatsApp
       await axios.post(
         `https://graph.facebook.com/v11.0/YOUR_PHONE_NUMBER_ID/messages`,
         {
           messaging_product: 'whatsapp',
           to: senderPhone,
           type: 'text',
           text: { body: answerText }
         },
         {
           headers: {
             'Authorization': 'Bearer YOUR_WHATSAPP_TOKEN',
             'Content-Type': 'application/json'
           }
         }
       );
   
       res.sendStatus(200); // Acknowledge receipt of the message
     } catch (error) {
       console.error('Error handling message:', error);
       res.sendStatus(500);
     }
   });
   
   const PORT = process.env.PORT || 3000;
   app.listen(PORT, () => {
     console.log(`Server is running on port ${PORT}`);
   });
   
   ```
   * **Replace**

     ```javascript
     YOUR_BRAINFISH_ACCESS_TOKEN
     ```

     with the token from Brainfish.
   * **Replace**

     ```javascript
     YOUR_PHONE_NUMBER_ID
     ```

     **and**

     ```javascript
     YOUR_WHATSAPP_TOKEN
     ```

     with details from your WhatsApp API setup.
3. **Start Your Server**:
   * In the terminal, run:

     ```javascript
     bash
     ```

     Copy code

     ```javascript
     node server.js
     
     ```
   * Your server should now be running and listening for incoming WhatsApp messages.


---

# **Step 5: Configure Webhook on Meta Developer Dashboard**


1. **Go to your WhatsApp Webhooks section** on the Meta Developer Dashboard.
2. Set the **Callback URL** to your server’s URL (e.g.,

   ```javascript
   https://yourdomain.com/webhook
   ```

   ).
3. **Verify the Webhook**:
   * You may need to respond with a verification token; add this to your code if needed.
4. **Save** your changes.


---

# **Step 6: Test the Integration**


1. **Send a WhatsApp Message** to your registered phone number (from Step 3).
2. **Observe the Response**:
   * Your server should receive the message, send it to Brainfish, and return an answer to WhatsApp.


---

## **Sample Interaction: Consumer Use Case**

* **Customer**: “What is Generative Language Models?”
* **Response**: “A Generative Language Model (GLLM) is a sophisticated AI model designed to generate coherent and contextually relevant text...”


---

## **Additional Configuration Tips**

* **Logging**: Use console logs or a logging service to monitor requests and troubleshoot errors.
* **Error Handling**: Update the

  ```javascript
  catch
  ```

  block in

  ```javascript
  server.js
  ```

  to handle specific errors (e.g., expired tokens).
* **Testing on Localhost**: Use tools like [ngrok](https://ngrok.com/) to expose your local server to the internet for testing webhooks.


---

## **Troubleshooting & Best Practices**

* **Token Management**: Brainfish and WhatsApp tokens may expire. Keep track of expiry and renew tokens as needed.
* **WhatsApp Message Limits**: Check WhatsApp’s message rate limits to avoid restrictions.
* **Compliance**: Ensure responses comply with WhatsApp's guidelines.


---

Following these steps will set up an automatic response system for WhatsApp using Brainfish API from scratch, enhancing customer engagement with accurate, context-sensitive answers. For more support, reach out to support@brainfi.sh.
