Building Rest API with Buildable and Twilio
Tags: saas, buildable, rest, api
Published: 2022-10-06 13:09:41

---
title: Building Rest API with Buildable and Twilio
published: true
description: 
tags: saas, buildable, REST, API
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
---

 Recently I came across [Buildable](https//buildable.dev) and was impressed with what I can do with it, so I decided to share my knowledge which I believe could be of use to someone. Buildable makes API development easy for developers without having to worry about Devops related stuff and how to scale your API. Today will be Building a RESTful API for creating orders.
To start, you need to create an account with [Buildable](https//buildable.dev), which you can do by linking your Github account.

### Creating Workflow

Go to [app](https://app.buildable.dev) and create a new workflow

![newIcon](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tqedovydemov8ei6g0ra.png)

![create-workflow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k832qq6yxa45l5ne6uer.png)

you can add a description if you wish and click the create button.
 Notice you have the body, action, and response tabs as seen below

![tabs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tcc7ypgd53daeppu8u4b.png)
 
- <b>Body:</b> Here you pass your request body when testing the API.
- <b>Header:</b> For adding request headers e.g auth token 
- <b>Action:</b> Here you can add different actions you are given out of the box like stripe, database integration, and more you can also add some of your logic here if required.
- <b>Response:</b> Here you add some logic and what you want to return as a response when the API is called.

### Adding Functionality

We will be adding a new action to create an order to our database which we will use MongoDB.
Click new action and search for MongoDB and select insert document, this will give you the ability to insert a new document to your collection. You should have something like this below

![action](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yl5l8y859u5u4vuiy4ru.png)
Here we updated your collection name to "test-order"
```javascript
  const { MONGODB_CONNECTION_KEY, collection, ...fieldsToInsert, productId } = input;
```
here we add the productId in the run function which will get from the body of the request to create an order
```javascript 
 const product = getProduct(productId)
  if (!product) {
    return {}
  }
```
checking if the product exists, if it does not we return an empty object
```javascript
  const order = {
      _id,
      createdDate,
      createdAt,
      name: product.name,
      address: "test address",
      status: "pending",
      productId,
      amount: product.amount,
    }

    const db = await getConnection(MONGODB_CONNECTION_KEY)

    const results = await db.collection(collection).insertOne(order)
``` 
if the product exists will create an order object and insert it into our collection.
Our run function should look like this at the end
```javascript
   const run = async (input) => {
  const { MONGODB_CONNECTION_KEY, collection } = input

  verifyInput(input)
  const { productId } = input
  // Write your logic here
  const product = getProduct(productId)
  if (!product) {
    return {}
  }
  try {
    const _id = cleanUUID()
    const createdDate = new Date()
    const createdAt = createdDate.getTime()

    const order = {
      _id,
      createdDate,
      createdAt,
      name: product.name,
      address: "test address",
      status: "pending",
      productId,
      amount: product.amount,
    }

    const db = await getConnection(MONGODB_CONNECTION_KEY)

    const results = await db.collection(collection).insertOne(order)

    return results
  } catch (error) {
    return {
      failed: true,
      message: error.message,
      data: {
        ...error.data,
      },
    }
  }
}
```
then now below the run function add this code
```javascript
 const products = [
  {
    id: 1,
    productId: 101,
    name: "noodles",
    amount: 50,
    currency: "aed",
  },
  {
    id: 2,
    productId: 201,
    name: "Pepsi",
    amount: 20,
    currency: "aed",
  },
]
function getProduct(id) {
  return products.filter((p) => p.productId === id)[0]
}
```
which is just mock data and a function that checks if the product exists.
 Go to the response and update the response tab to this
```javascript
  async function response({ body, headers, env, $actions }) {
	// Write your logic here
    const order = $actions.createOrder;
    // create product
     if (!order){
       return {
        status: 404,
        body: {}
      }
     }
     const msg = `Your order ${order.insertedId.toString()} is being created successfully`
     await notifyUser(msg, 'xxxxxxx', env)
  // send SMS/email to tell user order have been created
	return {
	  status: 200, // HTTP Response Status Code
	  headers: {}, // Response Headers
	  body: {
		...order,
	  },
	}
  }


async function notifyUser(msg, mobile, env) {
  const axios = require("axios");
  const client = require('twilio')(env.TWILIO_ACCOUNT_SID, env.TWILIO_AUTH_TOKEN ); 
 // the form should be your twilio number
  await client.messages.create({         
         to: mobile, body: msg, from: 'xxxxxx' }) 
}
``` 
So here we get the response from the action from ``$actions.createOrder`` if the project is empty means we don't have a product else it returns the order created and sends an SMS to notify the user the order has been created. To get your [twilio](https://twilio.com) credentials you need to create an account.

### Testing The API

  Now to test our API go to the body tab and add this snippet
```json
{
  "productId": 101
}
```
now click the save button to save all we did and click the run button you should get something like this
```json
{
  "acknowledged": true,
  "insertedId": "89bebecc38cb4db5ae9b68516ef0eceb"
}
```
Voila that how easy it is to create an API with Buildable. I hope you enjoyed this article, please don't forget to try using Buildable and sharing it with your friends. Also i will love to give kudos to Moe, Paul and Esther from Buildable.