Building REST API with Node.js

Search for a command to run...

No comments yet. Be the first to comment.
Twitter is one of the most popular social media platforms in the world, with over 330 million active users as of 2021. If you are interested in building a Twitter-like application, this tutorial will guide you through the process of building a FullSt...

Hey everyone, In this article, we will build our own Tic Tac Toe game using pure Javascript. https://youtu.be/lKe57l8sttw Code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE...

Hi everyone, In this blog, we will learn how we can create node.js functions locally and deploy them to AWS Lambda using serverless. So, let's get started. Step 1. Create an AWS Account ☁️ In order to deploy functions to AWS Lambda, you should have a...

Hey there, In this article, we are going to learn how you can upload any file to firebase storage. Uploading files to firebase storage is really easy. I would I recommend you to code along with me for better understanding. So, let's get started. Step...

Hey there, Welcome back. In this article, I would be showing you how I made a collaborative IDE with a video call. The main application of this application is that you can create a room and people can join the room. You have the ability to write mark...

A few years back, the only way to run a javascript code was in web browsers. But after the birth of Nodejs, we could run javascript code outside of the web browser.
Node.js provides a run time environment to run javascript code. It is built on the chrome’s open-source V8 engine.
After being said that let's build a real REST API in Node.js & Express from scratch.
I'll be guiding you step by step with a detailed explanation from installing node to building our restful API.
API stands for Application Programming Interface. Yes I know it’s too much jargon.
To download and install node js on your machine, head over to https://nodejs.org/en/ and select your download version.
There are two types of download version:
LTS — Long Term Support
Current Version
To Verify your installation open your terminal (macOS) or Command Prompt (Windows) and type “node — version”. This will show your current installed version of nodejs on your machine.
After you have successfully installed node on your machine, lets set up our project structure for building API.
Every node project has a file named as package.json. This file contains some configs and names about your project. This file also keeps the track of the dependencies and packages used in our project.
To create a package.json, In your terminal or command prompt type
npm init
in your project folder and press enter. At this step, npm would ask you some questions like name, description, etc. Keep pressing enter key to accept all at default names.
{
"name": "myapi",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Please do verify that package.json is created inside the folder.
Note: If you had a look on to our package.json file, there is a key named as “main” and value is “index.js”, which means that index.js is the entry point of our application. So we need to create an index.js file in our project directory.
Our Project Structure:
myApi
|- index.js
|- package.json
Before we get started to code our API we need to install some dependencies in our project.
Installing dependencies is really simple. All you need to type is a command in your terminal or command prompt.
Command:
npm install express
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
At this point a package.lock and node_modules folder would be created in your project directory. node_modules folder contains the source code of your all the dependencies that you install (express in our case).
Open your index.js file and code along with me.
// Import the Express using require() module
const express = require('express');
// Initalize express app
const app = express();
// Lets create Fake Data for api
const userData = [
{
id: 1,
name: 'Jhon',
age: 20
},
{
id: 2,
name: 'Jane',
age: 23
},
{
id: 3,
name: 'Tim',
age: 34
},
];
// Create Endpoints for API
// Endpoint 1
app.get('/api', function(req, res){
res.send('Welcome to our API')
})
// Endpoint 2
app.get('/api/users', function(req, res){
res.json(userData);
})
// Endpoint 3
app.get('/api/user/:id', function(req, res){
const id = req.params.id;
const user = userData.find(user => user.id == id);
if (user) {
res.json(user)
}
else {
res.send('No User Found')
}
})
// Start the Server
const PORT = 3000;
app.listen(PORT, function(){
console.log('Server Started')
})
So firstly we will import express in our application using require() function and store it into a variable express.
const express = require('express')
Now, the express module that we have just imported returns a function which we can store into a different variable. By convention it is named as an app;
const app = express()
Great going! Now let's create a fake array of users which we would serve to our clients as an API.
const userData = [
{
id: 1,
name: 'Jhon',
age: 20
},
{
id: 2,
name: 'Jane',
age: 23
},
{
id: 3,
name: 'Tim',
age: 34
},
];
Feel free to add more users or data. 😉
An API endpoint is a URL where users can access to our API.
Creating Endpoints (also known as routes) is really simple.
Syntax: app.<Request_Method>(‘ Endpoint ’, callback function)
Example: Suppose we want an endpoint named as posts that accept GET requests.
app.get('/posts', function(req, res){
// ... do stuff !
})
The callback function has access to two parameters i.e Request and Response respectively.
So now you know how to create endpoints lets create some for our API.
// Endpoint 1
app.get('/api', function(req, res){
res.send('Welcome to our API')
})
// Endpoint 2
app.get('/api/users', function(req, res){
res.json(userData);
})
// Endpoint 3
app.get('/api/user/:id', function(req, res){
const id = req.params.id;
const user = userData.find(user => user.id === id);
if (user) {
res.json(user)
}
else {
res.send('No User Found')
}
})
Now, please pay a little attention to endpoint 3.
app.get(‘/api/user/:id’, function(req, res){
})
Here “: id” at the end of the endpoint is a parameter.
Suppose user types **www.example.com/api/user/1, **then the value of id would be equal to 1. you got the point!
We can access these parameters by typing req.params.id where req is the request which we received from the first parameter of the call back;
app.get(‘/example’, function(req, res){}) ;
To send a response to the client we use the res parameter.
res.send(“Hey There”);
or JSON Response
res.json(object);
In the end, we have to start our server by listening to some PORT and trust me this is also really simple.
Just use .listen function that accepts two parameters, PORT number and a callback function (which gets called when our server starts).
app.listen(3000, function(){
console.log('Server Started');
})
In our example, we have used 3000 as our PORT number.
To start your server type
node index.js
in command prompt or terminal and your server would get started.
Navigate to your favourite web browser and visit localhost:3000/api

Visit: localhost:3000/api/users

Visit: localhost:3000/api/user/<id>
Example: localhost:3000/api/user/2

Follow me on social media:
Github: piyushgarg195
Linkedin: Piyush Garg