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:
Explanation:
  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 prakhar@knowshipp.com

Keep breaking, keep making!

Comments

Popular posts from this blog

Controlling Servo Motor with BLYNK app over WiFi

Build a facebook chatbot with API.AI (zero coding)