DEV Community

Bensigo Egwey
Bensigo Egwey

Posted on

Building Rest API with Buildable and Twilio

Recently I came across Buildable 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, which you can do by linking your Github account.

Creating Workflow

Go to app and create a new workflow

newIcon

create-workflow

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

  • Body: Here you pass your request body when testing the API.
  • Header: For adding request headers e.g auth token
  • Action: 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.
  • Response: 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
Here we updated your collection name to "test-order"

  const { MONGODB_CONNECTION_KEY, collection, ...fieldsToInsert, productId } = input;
Enter fullscreen mode Exit fullscreen mode

here we add the productId in the run function which will get from the body of the request to create an order

 const product = getProduct(productId)
  if (!product) {
    return {}
  }
Enter fullscreen mode Exit fullscreen mode

checking if the product exists, if it does not we return an empty object

  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)
Enter fullscreen mode Exit fullscreen mode

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

   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,
      },
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

then now below the run function add this code

 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]
}
Enter fullscreen mode Exit fullscreen mode

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

  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' }) 
}
Enter fullscreen mode Exit fullscreen mode

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 credentials you need to create an account.

Testing The API

Now to test our API go to the body tab and add this snippet

{
  "productId": 101
}
Enter fullscreen mode Exit fullscreen mode

now click the save button to save all we did and click the run button you should get something like this

{
  "acknowledged": true,
  "insertedId": "89bebecc38cb4db5ae9b68516ef0eceb"
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)