Back to the blog
Technology

Getting Started with Google Cloud Functions — Write/Deploy your first API in Node JS

author image

Karan Vyas

Date posted: September 17, 2019


As we have set up our google cloud function from the last blog , we are all set to deploy our first API. but before jumping into deeper on deploying API, I will quickly brief about topics we will cover in this blog,

First thing first, let’s talk about the technologies we are going to use, we will write our very first function/API in NodeJS 8. we will also cover creating a project in local so you can push to git, install necessary tools in the local machine, write a basic API in Node JS (some advanced use of API as well) and then deploy the functions locally and also push directly it to the server from the local machine.

For you to start it off all you need to have, is good knowledge of ‘Javascript'’. if you have then why to wait, let’s get started,

Installations

To start local setup we need node js installed locally. You can check that quickly running node -v.

We should test our API first in our local environment, for that, we are going to need Node.js Emulator.

Note:- Node 6 is just deprecated from the google cloud platform and we are going to use Node 8 for writing API’S make sure you have version 8 or above.

Installing Node.js Emulator

The Node.js Emulator is distributed as a standard npm package, so you can install it with a standard npm install command:

npm install -g @google-cloud/functions-emulator  

Or you can use Yarn if you prefer:

yarn global add @google-cloud/functions-emulator  

Since we have the emulator installed let’s start writing an API.

Installing Google Cloud SDK

  1. Download the official Google Cloud SDK zip file from here
  2. Unzip and save it at your desired location.
  3. Now open the folder which contains your unzipped google-cloud-sdk folder in the terminal.
  4. Run the command sh ./google-cloud-sdk/install.sh and give yes to all further prompts and you are done.

Now, just type gcloud -v to verify your installation.if you still facing some problems in installation you can follow official documentation here

Note:- The link to google cloud SDK is for macOS, you can also download zip for windows and ubuntu

Initializing Google Cloud SDK

Use the gcloud init command to perform several common SDK setup tasks. These include authorizing the SDK tools to access Google Cloud Platform using your user account credentials and setting up the default SDK configuration.

  1. Run the following at a command prompt:

    gcloud init --console-only
    

    Note:- You can also use gcloud init to autheticate via the browser

  2. Accept the option to log in using your Google user account:

    To continue, you must log in. Would you like to log in (Y/n)? Y
    
  3. At the command prompt, select a Cloud Platform project from the list of those where you have Owner, Editor or Viewer permissions:

    Pick cloud project to use:   
    [1] [my-project-1]   
    [2] [my-project-2] ...   
    Please enter your numeric choice:  
    

    You should see the list of the projects associated with your account, once you choose one of these you are good to go. if you want further configuration you can follow this

Write API

Before we start writing API, we just quickly set up a small project to manage all API

Project Setup

I am hoping you already have a project created on google cloud platform console if not then create here. I also have a blog for project setup and creation . Once you are done with this please open the terminal and start typing this

cd Desktop/  
mkdir node-api .  (Or create a folder on your own)  
cd node-api/  
touch index.js (or create a .js file)npm init  
(Hit enter / or change entries according to your project name untill you see this Is this OK? (yes))

Note: I am saving the project on the desktop you can choose other locations as well.

Let’s open node-api folder in VS-Code or any of your favorite editor.

you should see this on your left:

image1

Note:- We should have a separate file for each API and import in it index.js file for a better code structure. follow this

Create First API

It’s time to code. paste this into your index.js file.

exports.myFirstApi = (req, res) => {try {  
     res.status(200).send({ msg: 'Hello World!'});}  catch (error) {console.log("error" + error);res.status(500).json({ error: error });  }  
}  

Let’s deploy it in our local environment.

Deploy API

As we have Node.js emulator installed, let’s run the emulator and deploy the function.

functions starts

Note:- Always deploy functions from the directory where index.js and package.json file resides. and after running the command you will also see a table of deployed functions in local.

functions deploy myFirstApi --trigger-http

after a few seconds, you should see this.

image2

you can copy the resource URL and paste it in your browser or postman to see the result JSON.

image3

Yay! It worked, now time to deploy it on public URL so you can access it publicly. Good news is we are just one command away. we are gonna modify in the same command which we used to deploy it locally.

Just to be sure we don’t need to run Node.js emulator while deploying it publicly.

will take a while, after that you should see this

image4

Just copy your URL and start hit it from postman or browser.

Congrats! you have written and deployed an API within some time, that was crazy fast right? Basically, that is the biggest advantages of lambda functions. As we talk about Google Cloud lambda functions they also support dependencies installation and supported config files(if you want) along with API.

You can also check logs by sign-in to your g-cloud platform. it also supports environment variable

In Addition

Let’s write two API’s one of which fetches data from a server and send the response back to us, and the second one will read data from the local JSON file and send back to the user. with these API’s we will cover how we can install the external dependency, handle async calls during API and keep the additional file in server (Which can be a config file or database scripts).

I will use axios for external server calls, let’s install it.

npm install axios

First, we will write an API, which gets data from the server and send back to the user.

const axios = require('axios');//returns promise let getUserData = () => {return axios.get('https://jsonplaceholder.typicode.com/todos/1');}//return actual response from serverlet getData = async () => {let responseData = null;try {let res = await getUserData();responseData = res.data;console.log("the outuput::",responseData);} catch (error) {console.log("error" + error);} finally {return responseData;}}//Helper function to send error as responselet sendError = (res,errMsg) => {res.status(500).json({error: errMsg});}//The API to get user mock dataexports.getMockUserData = async (req, res) => {try {let userResponse = await getData();if(!!userResponse){res.status(200).send(JSON.stringify(userResponse));}else {sendError(res,'No data available');}} catch (error) {console.log("error" + error);sendError(res,'Internal Server Error! '+error.message);}}  

I have kept the code simple and ready to deploy instead of splitting into different files, although it is always good to make code reusable by splitting it into functions and files. I will leave that to you and won’t go deeper into that.

So now we write the second API, to read JSON from another file and server back as a response, this is so useful when you want to create config files and read it based on environment variables or etc. The use case is completely on you, so let’s code.

const fs = require("fs");exports.getUserDataFromFile = (req, res) => {try {let userId = req.query.userId || req.body.userId;let fileData = JSON.parse(`${fs.readFileSync('user.json')}`|| '{}');let userData = fileData[userId] || null;if(!!userData){res.status(200).send(JSON.stringify(userData));}else {sendError(res,'No data available');}} catch (error) {console.log("error" + error);sendError(res,'Internal Server Error! '+error.message);}}  

Note:- you can make these API calls from post and get both, by keeping that in mind, I am reading userId from parameters and request body both.

Don’t forget to deploy both APIs on the server.

gcloud functions deploy getMockUserData --runtime nodejs8 --trigger-http
gcloud functions deploy getUserDataFromFile  --runtime nodejs8 --trigger-http

If you are wondering, how we deploy the user.json file. we don’t need to actually, it will be deployed automatically since we read it in our function.

//user.json{"5": {"userId": 5,"id": 3,"title": "Welcome to the world!","completed": false}}

Since we have covered almost everything in this blog, one good thing left is how to make database calls and get data, (we can’t have file.json for everything right?). Here is the blog for that.

Browse all categories