Serverless REST APIs made simple with Cloud functions

Introduction

Serverless is one of the top keyword in the integration space right now. Everyone is talking about the serverless just to make sure that they are already in the flow.

What is Serverless?

Before we go deeper on how to write serverless APIs with Cloud function, I would like to give a quick introduction about serverless. The following is the given explanation from the wiki,

Serverless computing is a cloud-computing execution model in which 
the cloud provider runs the server, and dynamically manages 
the allocation of machine resources.

So, the server will be maintained by the cloud providers. Developers or business owners should write only the specific logic as a function, then deploy it into the cloud function infrastructure. So that the scalability and performance optimization will be handled by the cloud providers.

Traditional deployment

Mostly these kinds of deployment follow the monolith way of developing application and deploy everything in a VM or in a cloud. This will have some limitations with respect to scalability and better resource utilization. Moreover, this will also have some limitations on the heaviness of the deployment.

Micro deployment

This is mainly talking about container-based deployment. In recent times, everyone is talking about Docker and Kubernetes way of deploying applications. They will have a bunch of microservices and all of these services will work together to meet the customer use-cases. Each microservices will have different deployment lifecycles as well as a development strategy. Even though microservices bring lots of benefits, it also has its own challenges to manage.

Serverless deployment

This deployment model is one level down of microservice deployment. Here we are talking about each tiny functionalities can be deployed seamlessly into the cloud and serve better. This is also referred with the terms of function-as-a-service. There are lots of cloud vendors are supporting this way of deployment namely AWS Lambda, Google Cloud Functions, IBM Cloud Functions, Microsoft Azure Functions, Oracle Fn and Project Riff.

In this article, I am going to walk you through on how to develop a serverless REST APIs with Google Cloud Functions. I believe you have already gone through my previous article on setting up Cloud functions infrastructure. If not, I would recommend you to go through them first and then continue with this one.

Prerequisites

  • Firebase project
  • Firestore enabled for the project
  • Cloud function setup is ready locally

Firestore data structure

Since our datastore is Firestore, we will directly create some test data into Firestore collection as below,

In the above example, the collection name is countries. In which we have 3 documents store namely, aus, deu, and ind. Each document is defined with 4 properties (capital, code, currency, name) according to the country code. This is a simple data structure for this use-case.

Cloud functions

//functions/index.js

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp();
const firestore = admin.firestore(); //firestore reference

const express = require('express');
const cors = require('cors');

const app = express();
app.use(cors({ origin: true })); // Automatically allow cross-origin requests

app.get('/countries', (req, res) => {
  const countriesRef = firestore.collection('countries');
  countriesRef.get()
    .then(snapshot => {
      if (snapshot.empty) {
        res.send("Countries are not available");
      }

      var countries = [];
      snapshot.forEach(doc => {
        countries.push(doc.data());  
      });

      res.send(countries);
      return null;
    })
    .catch(err => {
      throw err;
    });
});

app.post('/countries', (req, res) => {
  res.send("/countries POST function called");
});

app.get('/countries/:id', (req, res) => {
  res.send("/countries/:id GET function called with id " + req.params.id);
});


exports.apis = functions.https.onRequest(app);

I have created 3 HTTP methods and finally which is attached with base path of /apis

Now you need to execute $ firebase deploy –only functions to deploy your functions. Once everything goes fine, you should be able to access your APIs with the following path.

GET https://us-central1-<projectid>.cloudfunctions.net/apis/countries
POST https://us-central1-<projectid>.cloudfunctions.net/apis/countries
GET https://us-central1-<projectid>.cloudfunctions.net/apis/countries/{id}

NOTE: <projectid> should be replaced with your real project id reference.

Now you should be able to access the above REST endpoints through any HTTP client.

//https://us-central1-<projectid>.cloudfunctions.net/apis/countries
//NOTE: Replace the projectid with yours.

[
  {
    "name": "Australia",
    "code": "AUS",
    "currency": "DOLLAR (AUD)",
    "capital": "Canberra"
  },
  {
    "capital": "Berlin",
    "name": "Germany",
    "code": "deu",
    "currency": "EURO (EUR)"
  },
  {
    "name": "India",
    "code": "IND",
    "currency": "RUPEE (INR)",
    "capital": "New Delhi"
  }
]

I believe you have got a fair idea on how to write Serverless REST APIs with Firebase Cloud functions. The above examples are not offering any complex functionalities. But this is done with the intention of explaining the concept easily. Keep watching this space for more detailed examples/use-cases in the future

I hope this has helped you to get the basics of serverless APIs with cloud functions. Please share it with your friends if you feel this helped you.

Happy coding!

API Evangelist | Chief Hustler @workrituals.com | Habit Coach | Madras Java User Group Leader
81FollowersFollow
0SubscribersSubscribe

Latest articles

Jakarta Tech Talk: Build Microservice using Microprofile + Helidon

Recently I gave a presentation on Jakarta Tech Talk series on 'Building a Microservice using Microprofile + Helidon. Enjoy watching the presentation...

Serverless REST APIs made simple with Cloud functions

Introduction Serverless is one of the top keyword in the integration space right now. Everyone is talking about the...

How to get started with Google cloud functions?

The 'Cloud Functions' is a Google technology bundled as part of the Firebase platform. It is a serverless backend to support our...

Why Firebase is a great technology for ‘Indie Makers’...

Firebase is a technology developed by Google. In this article, I am going to explore why Firebase is a great technology for...

Helidon: 2x productivity with Microprofile REST Client

We have already many articles before on how to write Microservice using the Helidon framework. We are going to further enhance our...

Similar articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here