Skip to main content

Build a REST API using Node and Express.js

Hello Sailors, if you are a programmer you would have heard about APIs or have developed APIs in JAVA, Python or any language. Today, we are going to build an API which sends random nutrition tips as response, with Nodejs and Express.js. Sounds interesting!

What is an API?

API stands for Application Program Interface. Ho ho ho! this just made my life, what an explanation! Well, an API is a set of functions and procedures that allow you to create applications which access the data of an application or service.

Why do we need an API?

When we want to build an android application, a web application and a desktop application because there are different type of users, so instead of building separate logic for all of these applications, we will build an API and all these applications will consume this API and serves the purpose.
Here's another example : You have built a printer which prints great on paper but still no one buys it because you do not provide them any tool to communicate with that printer. If someone buys it, need to implement the program that communicates with the printer and then it will work. That's lame! Yes, that's why printer companies always provide you with set of tools so that your other applications like notepad, MS Word will simply communicate with your printer using those tools which an API.

Benefits of API

1. Increased efficiency:
Providing API access allows for content to be created once and automatically published or made available to many channels.

2. Integration:
By creating APIs we are not just limited to one front-end, we can consume this on mobile application, web application or any desktop application.

That's seriously too much theory! Let's begin...

Things we need:

1. Node.js installed on your system.
2. Text editor, I would suggest you to use Visual Studio Code.

Create folder structure:

  1. We will create a folder "firstAPI" and open this folder in Visual Studio Code(later I will use VS Code for this).
  2. Open in-built terminal inside VS code using Ctrl + ~
  3. Type npm init to initialize the application. It will ask a few questions and create a package.json file containing those details.
  4. npm init
  5. Notice that by default main file is "index.js", this is your primary file where your API accept requests.
  6. You can see the entered details of your project in package.json.
Install Dependencies:
  • We are using Express.js to route requests and provide response to the user.
  • npm install express --save
  • You can now see the express dependency added to package.json file. The benefit of --save is that when you move deploy your application on server you do not need to copy your node_modules folder there, server will read the package.json file and install all the dependencies required for your application to run. Oh yeah!
Understanding the request and response:
1. Create index.js file inside firstAPI folder and add the code below:
const express = require('express')
const app = express()

app.get('/', function (req, res) {
  res.send('Hello World!')

app.listen(3000, function () {
  console.log('App is listening on port 3000!')
Explanation: We have imported express into our application using "require" function then created it's object to access it's functions.
The get function will received requests on root path (which is '/'), so by entering localhost:3000 on your browser "send" will send Hello World! as response to the request.
And, our app is available on port 3000.
2. Now, type node index.js on terminal to start your program.
node index.js

Open your browser and you should see Hello World! on localhost:3000 address.
Code for Nutrition Tips API:
  1. At line 11 you can see use() function called before get. This function is called middleware, it's purpose is to do some pre-processing before send the response i.e. checking authentication. '/' means all the requests received on the are logged first on console and the response is send using the next function.
  2. There is also next() function, it first logs the time stamp on console then transfers the control to the next function which is app.get(...).
  3. We have defined a list of Nutrition tips which we are fetching randomly in app.get() function. This function will only respond to requests received on path '/nutritionTips'. We set the header as JSON and then sending the string of JSON using send function.
Run the app using index.js on the terminal and see the JSON results on your browser on address : localhost:3000/nutritionTips
We have now successfully built our first API using Node.js and Express.js which can be consumed on any web, mobile or desktop application.

Future steps, learn to deploy the node applications on Heroku, Azure or AWS cloud so that your APIs would be available for all. Learn to authenticate your APIs so only the restricted user can access your API.

That's it, Sailors! Suggestions and improvements are always welcome. Write to me at

Keep breaking, keep making!


Popular posts from this blog

Controlling Servo Motor with BLYNK app over WiFi

Hello Shippers, hope you are having a great time! Today, we are gonna build a simple project of controlling servo motor with BLYNK app over Wifi.
Overview: The slider on the blynk app will send a value to the NodeMCU/ESP8266 and this value will be written on PIN 8 and the servo rotates that much degrees. That's the way we are controlling servo motor. Ahaa!

Things we need:Hardware:Servo SG90NodeMCUMicroUSB cableJumper WiresSoftware:Arduino IDEBLYNK appCircuit:
Connections:D8 pin of NodeMCU connects to Command pin of Servo Motor.3V3 PIN of NodeMCU connects to Power PIN of Servo motor (usually RED one).GND PIN of NodeMCU connects to GND of servo motor (usually BLACK one). Simple connections, huh!
BLYNK app Setup on phone:Create a New Project in BLYNK app.Write Project Name and Select ESP8266 or NodeMCU from dropdown.An AUTH token will be sent to your registered email, note this down.Tap on the screen and add a SLIDER widget on the screen.Tap on the Widget, select Digital PIN 8 and Start…

Setup Mosquitto MQTT broker in Windows

MQTT (Message Queueing Telemetry Transport) is a Client Server messaging transport protocol. It provides a lightweight method of carrying messages using a publish/subscribe model. The pub/sub model being lighweight makes it suitable for IOT messaging with low power devices, sensors, phones or microcontrollers. How MQTT works? MQTT follows publish/subscribe model which is alternative to server-client model where client communicates directly with server. The pub/sub model defines the client which send a message(publisher) to another client which received that message(subscriber). The subscriber and publisher are unaware of the presence of each other. The main part, which we call the Broker, which our both publisher and subscriber are aware of, filters all the coming messages and distributes them respectively.

Now we know what is MQTT and how it works. Let's dive in to set this up on Windows 7/8/10.
Mosquitto: This is an open source message broker used for handling lightweight data t…

Time scheduled electric switch controlled with Blynk app

Most of the times when we go out of home for some days, we think of having some device that could switch ON/OFF (let's say) Refrigerator (or any other important appliance)for some hours during the day. Today, we are going to make such time scheduled electric switch which switches ON/OFF at times which we set the in our Blynk app. Woah!

Let's begin!
Things we need:
Hardware:5V relayNodeMCUJumper wiresBreadboard3V3 and 5V power sourceElectrical WiresSoftware:Arduino IDEBLYNK app It's circuit is same as we have created for our Smart Switch. So, if you already have that circuit set up, go ahead with Blynk app set up and Start playing.
Connections:D5 pin of NodeMCU connects to IN1 pin of 5V relay.3V3 of NodeMCU connects to 3V3 powers source and GND to GND.Vcc of relay connects to 5V source and GND to GND.Live wire is connected directly to appliance.Neutral wire from source comes to relay NC pin and another wire goes out from COM pin which is connected to the appliance.Let…