Build a SMS Nutrition Bot with Twilio, Nutritionix, and Cloud Functions
Get the nutritional content of your favorite foods with a single text
Have you ever been on-the-go and wanted to quickly know the nutritional content of something you’re currently eating? This tutorial will guide you though the process of building a SMS bot that you can interact with to get the nutritional information of common foods so you don’t have to manually look them up. It will also serve as an introduction to technical concepts such as web APIs and serverless computing.
At the end of this guide, you’ll have your own working version of a simple SMS bot that you can build upon to fit your own needs. More importantly, you’ll also have a full understanding of what goes on behind the scenes from the moment you hit send up until when you get a response with nutrition data. Once you’re done, you should be able to interact with your bot in a manner similar to the images below. With that, let’s get started!
Before jumping into any setup or implementation details, we’ll break down two terms which are referenced frequently in the sections below.
An API (application programming interface) is a way for two pieces of software to communicate with one another. This is accomplished by an interface (or outline) of how this interaction must occur.
APIs are used everywhere in software — from exposing functionality offered by a 3rd party service to providing an interface for your computer’s operating system. They are powerful in that they allow code to leverage the functionality of other code without knowing its underlying implementation. APIs allow you to think about parts of software and their interaction with other entities in abstraction, thereby enabling you to focus on a particular component without needing to know how all of its neighboring pieces work.
A SDK (software development kit) is a collection of tools that is provided to developers to help them build their applications. SDKs are typically designed for specific programming languages or platforms, and include a range of resources such as APIs and libraries, code samples, guides, and standards.
SDKs allow developers to leverage a set of established resources and best practices. They typically provide tools to run, test, and debug applications as well as solutions to commonly encountered problems such as data storage, error handling, and authorization.
Technologies Used in this Tutorial
Twilio is a cloud communications platform that enables developers to build web and mobile applications that utilize messaging, voice, and video functionality.
Twilio’s SMS API allows applications to send and receive text messages globally, and will serve as the means for sending messages to and receiving responses from your bot.
Nutritionix is the world’s largest verified nutrition database. They help over 25,000 restaurants manage and publish their nutrition data, as well as offer an API for developers to integrate nutrition and exercise information into their applications.
Nutritionix’s food lookup API enables you to pass in user provided text and receive back nutrition data from extracted food items.
The Google Cloud Platform (GCP) is a suite of cloud computing services that run on Google’s infrastructure. These services enable developers to build and deploy their applications in a secure, reliable, and scalable manner.
One of their services — cloud functions — allows you to write code that is run in response to specified events, and scales automatically without the need of managing servers. We’ll go into more depth about the benefits of serverless computing and how cloud functions work later in this tutorial.
Prerequisites and Setup
You’ll also need to follow the steps below to ensure your environment is up-to-date and that you have the necessary setup for your bot.
For this tutorial, you must have Node.js installed (v8.0.0 or above). To check your version of Node, run this command:
Google Cloud Account
In order to utilize Google Cloud Functions, you’ll need to set up a GCP account, create a project, and install the Google Cloud SDK.
1. If you have not previously used GCP, create a free account
- Create a GCP account here.
- When you first start using GCP, you’ll receive $300 of free credit to begin experimenting with their wide range of services.
2. Create a new project in the GCP console
- Follow this guide for creating a new project.
- Make sure to note your project id, which will be used in the next step.
3. Enable project billing
- Enable billing for your project.
- You must provide billing details for your account, but you won’t be charged once your free trial period ends or you have used up your trial credit. Rather, you’ll receive an email asking you to upgrade to a paid account.
4. Install the Google Cloud SDK
- Follow this guide to install the Google Cloud SDK.
- The Google Cloud SDK provides a set of command line tools for directly accessing GCP services and developing applications in the language of your choice using Google Cloud.
Twilio Account and API Key
You’ll also need to create a Twilio account and set up a phone number to send your bot messages.
1. Create a Twilio account and phone number
- Create a Twilio account here and ensure that you’re logged in.
- Navigate to your console’s home page and click Get Started > Get your first Twilio phone number. Confirm your new number.
2. Configure Twilio to trigger your cloud function for incoming messages
- Navigate to the Manage Numbers section of the Twilio console. You should see the phone number that you just created. Click on this number.
- Scroll to the bottom of the page. You’ll see a section titled Messaging.
- In the sub-section titled A Message Comes In, for the webhook, specify the following url, replacing PROJECT_ID with your GCP project ID.
- Click Save to save your changes and navigate to your Twilio account settings page.
- Under LIVE Credentials, click the AUTH TOKEN section to view your auth token. Save it somewhere safe for later use.
Nutritionix Account and API Key
To be able to make requests to the Nutritionix API, you’ll need to have an account and create an API key.
1. Sign up for a Nutritionix account
2. Create an API key
- Click the tab View API Keys on the Nutritionix home page, which will take you to a page with your application details.
- Under Application Keys, click the Create New Key button. This will generate a new API key that should immediately be visible on the page.
- Both the application id and the application key will need to be included in each request to the Nutritionix API. Save these for later use.
Note: For this tutorial, you’ll be using the free tier for all of the APIs and services utilized to get your bot up and running. However, it is up to you to be mindful of rate limits and billing costs if you decide to build upon this project for more extended use.
Before diving into the implementation of your bot, it’s helpful to understand the why and how behind the technologies you’ll be using and the manner in which they communicate. We’ll walk through each one of these steps below.
1. Text message sent to bot
- A user first initiates the logic flow above by sending a message to a Twilio owned phone number.
- Your Twilio phone number can be configured with a pre-specified webhook URL. With each text message received, Twilio sends a request to this URL.
- A webhook (sometimes referred to as a reverse API or web callback) is an event-driven way in which an application can receive information from other applications as it becomes available. In contrast to the format followed by a traditional web API where a client-side application makes a request to a server-side application and waits on a response, with webhooks, you can provide a URL and your client will be notified with the appropriate data when certain events occur on the server side. This eliminates the need for continuous polling to check for new events.
- Your webhook will be associated with your cloud function — causing your cloud function to be invoked with each new message.
2. Cloud function invoked
- Once a text is sent, Twilio will use your provided webhook URL to trigger your cloud function. Your cloud function is responsible for verifying that the request came from Twilio, extracting the body of the text, and making a request to the Nutritionix API to get back nutrition data.
- Cloud Functions provide you with an event-driven way to execute code without having to provision servers or manage underlying infrastructure. You can read more about cloud functions in Google’s documentation.
- Cloud functions are often discussed in the context of serverless computing, a term referring to a model where a cloud provider — not an individual or technical team — oversees the provisioning, management, and upgrading of servers.
- Contrary to the name, this model does not refer to an absence of servers, but rather an abstraction of them to the level where you only have to focus on the logic of your code — not the environment it runs in. Instead, the necessary resources to run your code are allocated and de-allocated in response to pre-defined events.
- Pricing for serverless solutions also differs in that it is based off of the amount of resources used rather than a pre-defined unit of capacity. You are only billed for your Cloud Function’s execution time and pay nothing when your function is idle. This can be really beneficial for applications that have low or fluctuating volumes of usage. For example, in this application, you might only make a few requests for nutrition data a day. Rather than having your app up and running 24/7 on a server listening for requests, you can have the necessary resources allocated on the occurrence of a particular event and freed up afterwards.
3. Nutritionix request for nutrition data
- Your cloud function will make a POST request to the nutrients endpoint of the Nutritionix API with this format — passing in user-entered text in the request body.
- The API will handle taking the passed in text and getting a nutrient breakdown of the food contained within it.
4. Nutritionix response with nutrition data
- The Nutritionix API will send back a response to your Cloud Function in the following format.
5. Cloud function response
- Your cloud function will take the response from the Nutritionix API, extract relevant information (e.g. serving size, calories, sugars, protein, etc.), and format a response that is ultimately returned along with additional information about any actions Twilio should perform.
6. Bot response with nutritional data
- Lastly — as an end user — you’ll receive a text back consisting of a nutritional breakdown of the food you entered, or a response indicating that your message couldn’t be processed.
Set up your project
1. Navigate to the local directory where you want to place your files and run the following command to initialize your project:
2. Install the Twilio Node package whose documentation can be found here. This will allow you to preform actions such as validating incoming requests and sending responses.
npm install --save twilio
Add your code
1. Create a file called
config.js that mirrors the first GitHub gist below. This will house your auth tokens, API keys, or any other secret configuration information. Replace all values with the appropriate values noted in the sections above.
Note: If you plan to push this code to GitHub, make sure not to commit this file, or look for more secure ways to load in these values.
2. Create another file
index.js that will house the body of your cloud function. Copy and paste the contents of the second gist into this file.
Deploy your function
On the command line, run the command below to deploy your function. You should get a message stating that your function is being deployed and that this process can take up to two minutes. Once the deployment is done, you should see a success message, as well as general information about your function.
gcloud functions deploy reply --trigger-http
Test out your function
Now it’s time to test your function! On your phone, send a text to the number that you created through Twilio (to find it again visit the Manage Numbers section of the Twilio console).
In the body of your text, enter one or more food items that you would like to find nutrition information for. You should get back a response similar to the screenshots at the start of this article — telling you the nutrition information for each of the servings of your mentioned food items.
Access your function’s logs
To view your cloud function’s logs, navigate to the GCP console and make sure you have the correct project selected. On the side nav bar, under Compute, click on Cloud Functions. You should then see your function (reply) as in the screenshot below. Click on your function’s name.
Next, you should see a screen for your cloud function’s invocations over a given period of time. Here you can also examine your function’s execution time and memory usage. Once you’re done inspecting your function, on the top of the page, click View Logs. You should be brought to a page like the one below.
On this page, you’ll be able to see any GCP or custom generated logs, as well as any errors if they exist. You can use these logs to help debug your function if any issues arise.
Conclusion and Challenge Ideas
Congrats! You’ve built a simple bot which you can text food choices to and get back nutrition information. Through this process, you’ve also been introduced to some of the benefits of serverless computing, and APIs that you can use to develop future projects.
Want to take this project a step further? Here are some ideas of ways you can further extend this project to make it more useful:
- Give your bot some personality and add more tailored responses
- Add the ability for users to determine whether a given food contains a specific allergen
- Enable your bot to respond to messages that contain images using the Google Cloud Vision API