Write to a Notion Database via SMS with Twilio Serverless, the Notion API, and JavaScript
Tags: notion, javascript, webdev, tutorial
Published: 2021-06-14 20:58:22

---
title: Write to a Notion Database via SMS with Twilio Serverless, the Notion API, and JavaScript
published: true
description: Learn how to write to a Notion database via SMS using the Twilio Serverless Toolkit and the Notion API in JavaScript.
tags: notion, javascript, webdev, tutorial
cover_image: https://twilio-cms-prod.s3.amazonaws.com/images/UIJVbjK0OPTKzUWDNIZwKTCVnNiLY9IW5R5DXgvdsuhL74.width-808.png
---
This blog post was written for [Twilio](https://www.twilio.com/) and [originally published on the Twilio blog](https://www.twilio.com/blog/write-to-notion-database-via-sms).

Notion is an app that bills itself as "an all-in-one workspace where you can write, plan, collaborate and get organized", letting you take notes, add tasks, manage projects, and more. They [recently released their API](https://developers.notion.com/). Read on to see how to write to a Notion database using [Twilio Programmable Messaging](https://www.twilio.com/docs/sms), the [Twilio Serverless Toolkit](https://www.twilio.com/docs/labs/serverless-toolkit), and [Twilio Functions](https://www.twilio.com/docs/runtime/functions).
![gif showing sending SMS text saves to Notion database](https://twilio-cms-prod.s3.amazonaws.com/original_images/IU5ocU0J1Kw8eigqT0J-LslgJxKRjeb8jkShRrf7T2dM3_2rtEn96uDwVAOOIaMpTCgsqbs0VG2PX2)

### Prerequisites
1. A Twilio account - [sign up for a free one here and receive an extra $10 if you upgrade through this link](http://www.twilio.com/referral/iHsJ5D).
2. A Twilio phone number with SMS capabilities - [configure one here](https://support.twilio.com/hc/en-us/articles/223135247-How-to-Search-for-and-Buy-a-Twilio-Phone-Number-from-Console).
3. Node.js installed - [download it here](https://nodejs.org/en/download/).
4. Notion account - [download the Mac or iOS app here](https://www.notion.so/desktop) and make an account (or you can just make an account at that link and use Notion in the browser).
5. A personal phone number to test the project.

### Get Started with the Notion API
Go to the [Notion API website](https://developers.notion.com/) and make sure you are logged into a Notion workspace as an Admin user. If you're not an Admin in your current workspace, [make a new personal workspace for free here](https://www.notion.so/Create-join-switch-workspaces-3b9be78982a940a7a27ce712ca6bdcf5#9332861c775543d0965f918924448a6d). From the Notion API site, click on My integrations in the top right corner.
![my integrations in the top right corner](https://twilio-cms-prod.s3.amazonaws.com/images/DMLqaGE_f1thHId6KtkzSZwwR6t3Zmydj9voVfI-UorMRk.width-800.png)
Select <em>New integration</em> and on the following page, give your integration a name like <em>general-db</em>. For the purposes of this post, the integration type can be <em>internal</em>.

After clicking <em>Submit</em>, you will be taken to a page with your integration's <em>Internal Integration Token</em>. Copy it and keep it hidden for later.
![page showing internal integration token for your integration](https://twilio-cms-prod.s3.amazonaws.com/images/IllljU9gH8p0pIkJ_qriA71hPagzZmJYNU-WUytUWf1_yq.width-500.png)
Make a new Notion page in your workspace either in your Notion app or at notion.so by clicking the plus sign next to Workspace. Your Notion workspace might have an <strong>Add a Page</strong> button beneath all the workspaces which you would click instead, like this.
![Add a page button](https://twilio-cms-prod.s3.amazonaws.com/images/X292TNfg6GCAhtKSAwpE2DrGA-plDq2F5lqll10vNasD7O.width-500.png)
For this blog post, I made a workspace called <em>Trip to-do's</em> and then added a table as shown in the gif below: type "/" and select <em>Table-Full page</em>.
![gif showing add full table](https://twilio-cms-prod.s3.amazonaws.com/original_images/Va0Y5RZW1alsLTZ6W_aUToCru1JJD9TIcKL-8dwV05oznbFMMsVOQUCUh5VysyKv_HglKWrk757JWK)
This inserts a new database into our workspace. You can read more on the [types of databases in Notion here](https://www.notion.so/Intro-to-databases-fd8cd2d212f74c50954c11086d85997e#13b4ab72cb8948ebbf67e3799d7adb55).

The workspace organization should look similar to the "Trip to-do's" directory with the database named "SoCal to-do" nested in the project workspace as seen in this example:
![workspace organization with nesting](https://twilio-cms-prod.s3.amazonaws.com/images/d_y1LHMPvi4kSDvgWiYyU0bidt-btdmNOrVEvDVJK2pp8Z.width-500.png)
Integrations don't have access to any pages or databases in the workspace at first: a Notion user needs to share certain pages with an integration so that the pages can be accessed using the API and keep the information in Notion secure.

To let the Notion API access our database, click <em>Share</em> in the top right of your database (in the workspace) followed by the blue <strong>Invite</strong> button. Under <em>Integrations</em>, click <em>Trip to-do</em>'s workspace.
![share to web button](https://twilio-cms-prod.s3.amazonaws.com/images/aZkKEu5mikt954ZNvxyt8bhCXItjpTwUy6BQIXzPIK135e.width-500.png)
You can see more information on sharing a database with your integration here on the Notion API website.

Give your database a title and some column names. This blog post's database is named "SoCal to-do". The column names reflect the data we want to keep track of such as <em>Name</em>, <em>What</em>, and <em>Where</em>. Set these in the Notion app like below:
![column table names](https://twilio-cms-prod.s3.amazonaws.com/images/nEzvtE24svbqgkei8CQDnerO-ef76tPKKVo1ZAQ9Z42x0Z.width-500.png)
Take note of the ID of the database you just created. Open Notion in a browser and view the database as a full page. The database ID is in between the URL after notion.so and ends before the question mark. The ID is 32 characters long with numbers and letters--copy the ID and save it somewhere you can easily find soon.

The database in this article begins with <em>dcfc</em> and ends with <em>e9e</em> as seen below:
![database URL](https://twilio-cms-prod.s3.amazonaws.com/images/CYamw7_d1ZsGSYgc6PJjPCm8fk5gU7l6u0Ngn2UutdbRbA.width-500.png)
Make sure that your database link does not contain your Notion username. If you see this, you may have to make a new database under a different project workspace so that it looks like the image above.

So far, we can add items to the database in Notion, but what if a user does not have Notion? Now we can add Twilio to the project so that non-Notion users can fill the database via SMS!

### Get your App Up and Running Quickly with the Twilio Serverless Toolkit
The Serverless Toolkit is CLI tooling that helps you develop locally and deploy to [Twilio Runtime](https://www.twilio.com/docs/runtime). The best way to work with the Serverless Toolkit is through the [Twilio CLI](https://www.twilio.com/docs/twilio-cli/quickstart). If you don't have the Twilio CLI installed yet, run the following commands in the terminal to install it and the Serverless Toolkit:
```bash
npm install twilio-cli -g
twilio login
twilio plugins:install @twilio-labs/plugin-serverless
```
Run the following commands to create your new project and install the lone requirement `superagent` - an HTTP client library to make HTTP requests in Node.js:
```bash
twilio serverless:init notion-api-twilio-sms --template=blank
cd notion-api-twilio-sms
npm install superagent
```
Edit the `.env` file and add an environment variable called <em>NOTION_API_KEY</em> for your Notion API key.
### Make a Twilio Function with JavaScript
`cd` into the `/functions` directory and make a new file called `write_to_db.js` containing the following code:
```javascript
const superagent = require('superagent');
exports.handler = async function(context, event, callback) {
  const twiml = new Twilio.twiml.MessagingResponse();
  let inbMsg = event.Body.trim();
  let propObj, firstCell, secondCell, thirdCell;
  let count = (inbMsg.match(/,/g) || []).length; //# of commas means # columns sent
  //check count of commas in inbound message: this will affect the Notion database columns we write to
  switch(count) {
    case 0: 
      firstCell = inbMsg;
      propObj = {
        "Name": [
          {
            "text": {
              "content": `${firstCell}`
            }
          }
        ]
      }
      break;
    case 1: //1 comma = 2 columns
      firstCell = inbMsg.split(',')[0];
      secondCell = inbMsg.split(',')[1];
      propObj = {
        "Name": [
          {
            "text": {
              "content": `${firstCell}`
            }
          }
        ],
        "What": [
          {
            "text": {
              "content": `${secondCell}`
            }
          }
        ],
      }
      break;
    case 2: //2 commas, 3 columns
      firstCell = inbMsg.split(',')[0];
      secondCell = inbMsg.split(',')[1];
      thirdCell = inbMsg.split(',')[2];
      propObj = {
        "Name": [
          {
            "text": {
              "content": `${firstCell}`
            }
          }
        ],
        "What": [
          {
            "text": {
              "content": `${secondCell}`
            }
          }
        ],
        "Where": [
          {
            "text": {
              "content": `${thirdCell}`
            }
          }
        ]
      }
      break;
  }
  superagent.post(`https://api.notion.com/v1/pages`, 
  { "parent": { 
    "database_id": `REPLACE-WITH-YOUR-DATABASE-ID`
  }, "properties": propObj
})
  .set('Authorization', `Bearer ${context.NOTION_API_KEY}`)
  .set('Content-Type', 'application/json')
  .set('Notion-Version', '2021-05-13')
  .then((res) => {
    twiml.message(`Wrote ${inbMsg} to the Notion page!`);
    callback(null, twiml);
  })
  .catch(err => {
  twiml.message(`Error: ${err.message}`);
    callback(null, twiml);
  });
};
```
This code imports superagent so that we can handle HTTP requests in Node.js. It also makes a [Twilio Messaging Response object](https://www.twilio.com/docs/sms/api/message-resource) which retrieves the inbound text message and checks the number of commas to decide which Notion database columns to post to.

The inbound message is parsed to separate the input based on commas and an object is passed to the Notion API's `properties` parameter which uses property names or IDs as keys. For more information on the Database object, check out [this section of the Notion API documentation](https://developers.notion.com/reference/database#database-property).

With <em>superagent<em>, we hit the Notion API's `pages` endpoint with the database ID to write content to the database. We set our Notion API key, the `content-type`, the Notion version, and then send a text message confirmation response back so the user knows what they texted was written to the shared database.

You can [view the complete app on GitHub here](https://github.com/elizabethsiegle/sms-to-notion-db).

### Configure the Function with a Twilio Phone Number
To open up our app to the web with a public-facing URL, go back to the <em>notion-api-twilio-sms</em> root directory and run `twilio serverless:deploy` to deploy the app. This will return some information including a few URLs as shown below:
![generated Function URLs when deployed](https://twilio-cms-prod.s3.amazonaws.com/images/PPqhDVUQa1IOQRy09a6oXxokvw7VMtkKFCkDVXBey9ZRrk.width-500.png)
Grab the Function URL ending in '/write_to_db' and run these commands:
```bash
twilio phone-numbers:update {YOUR-TWILIO-NUMBER} --sms-url {https://YOUR-URL-HERE.twil.io/write_to_db}
```
This connects the Twilio phone number to the deployed Function URL. If you view the phone number in your Phone Numbers Console, it will still show up there as a "Function" and not a "Webhook URL". You can now text your Twilio number things to do with its name, what, and , where separated by commas and have it written to your Notion database.
![text body saved to Notion database](https://twilio-cms-prod.s3.amazonaws.com/original_images/IU5ocU0J1Kw8eigqT0J-LslgJxKRjeb8jkShRrf7T2dM3_2rtEn96uDwVAOOIaMpTCgsqbs0VG2P_yOZIRmP)
### What's Next for Twilio Serverless and the Notion API?
There is a Notion integration that uses SendGrid to send an email whenever the <em>Status</em> property of a page in a database is updated, showing how Notion can cause an external action, and you can use the [Notion API](https://developers.notion.com/) for so much more!

Let me know online what you're building with Twilio Serverless or how you use Notion.