Building Rest API with Buildable and Twillo

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 relat…


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Bensigo Egwey

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;

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 {}
  }

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)

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,
      },
    }
  }
}

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]
}

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' }) 
}

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
}

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"
}

Vallah 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.


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Bensigo Egwey


Print Share Comment Cite Upload Translate Updates
APA

Bensigo Egwey | Sciencx (2022-10-06T13:09:41+00:00) Building Rest API with Buildable and Twillo. Retrieved from https://www.scien.cx/2022/10/06/building-rest-api-with-buildable-and-twillo/

MLA
" » Building Rest API with Buildable and Twillo." Bensigo Egwey | Sciencx - Thursday October 6, 2022, https://www.scien.cx/2022/10/06/building-rest-api-with-buildable-and-twillo/
HARVARD
Bensigo Egwey | Sciencx Thursday October 6, 2022 » Building Rest API with Buildable and Twillo., viewed ,<https://www.scien.cx/2022/10/06/building-rest-api-with-buildable-and-twillo/>
VANCOUVER
Bensigo Egwey | Sciencx - » Building Rest API with Buildable and Twillo. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/10/06/building-rest-api-with-buildable-and-twillo/
CHICAGO
" » Building Rest API with Buildable and Twillo." Bensigo Egwey | Sciencx - Accessed . https://www.scien.cx/2022/10/06/building-rest-api-with-buildable-and-twillo/
IEEE
" » Building Rest API with Buildable and Twillo." Bensigo Egwey | Sciencx [Online]. Available: https://www.scien.cx/2022/10/06/building-rest-api-with-buildable-and-twillo/. [Accessed: ]
rf:citation
» Building Rest API with Buildable and Twillo | Bensigo Egwey | Sciencx | https://www.scien.cx/2022/10/06/building-rest-api-with-buildable-and-twillo/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.