Part 01_Build a RESTful API using Node.js Express , MongoDB and JWT for authorization from the ground up for Beginners🚀

This article is the first in a series of articles where we are going to build a RESTful API from scratch. How important is this going to be? If you are getting into MERN/MEAN stack development or trying to lay your hands on backend development with node.js, this article is going to be super important and helpful. This article consists of the following:

  1. REST API introduction

Oh , you are not a developer, programmer, someone who writes code with an understanding?? Wait !!! The beginning section of this article is for you. You might want to know what an API is at least because without your knowledge, you are using APIs on a daily basis. First lets see what an API is.

What is an API?

The most common and simplest explanation of an API could be given by using a weather app on your mobile phone.

The developer who made the mobile app has nothing to do with setting satellites above the atmosphere of the earth to monitor weather.

Its just the companies who made the satellite and set into space🚀, have made the information gathered by the satellite about the weather accessible to the developers. How have they made this accessible? It’s by using something called as an API ( Application Programming Interface).

An API can also be called as an Abstraction layer. Abstraction is simply a way of organizing the complexity of a system so that complicated actions can be handled in a simple way. The developer who built the mobile application knows nothing about how the satellite gets its job done. It’s none of his concern. But what matters to him is the data the satellite gives. The developer uses the data and displays it on a beautiful User Interface and provides with multiple functionalities.

You might want to stop here if you are not interested in learning how to code to build an API yourself. Its going to get a bit technical from this point on.

What is a REST API?

Now that you have a basic idea of what an API is, in web development specifically, an API often refers to the way in which we retrieve information from an online service. There are thousands and thousands of API’s out there. Some popular ones are the

  1. google API’s to integrate Google Sign-In functionality to your application

The list just keeps going on. So far we’ve talked about API’s and we are going to build a REST API. But what is a REST API? To begin with REST stands for Representational State Transfer.

Not all API’s are RESTful but all RESTful services are APIs’.

REST is a type of API and for an API to become RESTful it should meet with certain criteria/constraints. We are not going to talk about the constraints here as this series of articles are written aiming at building one. Just for the knowledge, if an API serves data in JSON or XML or any other format(but most commonly JSON) it is the expression used to define a RESTFul API but be sure to checkout the REST API constraints.

So a basic knowledge of API’s ,what makes an API RESTful and a basic knowledge of Node.js is expected. We’ll be going through Express.js from the very beginning so no knowledge of Express.js is expected to follow this tutorial.

One more important thing, we are going to use ES Modules instead of CommonJS modules so make sure a recent version of Node.js is installed. You could check your Node version by running node --version on your terminal.

Express.js

https://expressjs.com/

We could create the API just by using node without using any frameworks, but using Express gets the same job done much more easily with a less amount of code.

Express is called an unopinionated, minimalistic framework because, unlike most javascript frameworks such as Angular, React etc, there isn’t a standard workflow and express isn’t very complex.

I’ll be using the Visual studio code text editor and this is what we have right now, just an empty server.js file. And we are going to do this from scratch as promised..

1. REST API

NPM init

01) First we have to run npm init,on the terminal which initializes an existing or new package.json file. It will ask a bunch of questions and then create a package.json file for you but you can skip the questions by running on the terminalnpm init -y command.

Why do we need a package.json file? If we are installing 3rd party packages locally on our project, someone needs to keep track on these dependencies or the external packages that our project depends on. For an example in this project we are going to have a couple of external packages such as express, nodemon, JSON Web Tokens installed locally on our project. So the package.json file keeps track on these dependencies. How? We’ll see in a bit.

After running npm init -y on the terminal, a package.json file is created as shown above.

Installing Express locally

02). In order to create a server, we need to have Express installed on our machine locally.

This is the Node Package Manager, so if you want to use external packages that are not available in the node core, you have to install it from the NPM. There are thousands of pre-built packages and express is what we are going to download now from the npm.

Search for Express on the npm website and you will be directed to the following web page.

Lets see what happens when we install Express.js locally on our project.

As you can see a "dependencies": { "express : "^4.17.1" } gets added to your package.json file and a node_modules folder gets created. node_modules folder contains all the externally downloaded packages that we install locally on our computer and we don’t need to know what’s in it. Simply, if you delete this folder , you’ll have to re-install the dependencies of your project. Another file by the name package-lock.json gets included along with the installation of express. This file consists of the information of the versions of the node_modules and we don’t have to worry about this file as well.

Creating an Express app

03). Now that we have installed express.js locally on our machine, its time for us to create an express app .

const app = express() Initializes an express app.

app.listen() is passed two parameters. The first one is the port number that our server is listening to , for requests from the browser. The second parameter is optional and it is a callback function. PORT 3000 is a common port number that we use for development.

This is all it takes to create a server listening for incoming requests on a certain port on our localhost which is our machine.

Now we need to send a response to this incoming request. Before learning how to send a response, you’ll probably need to know what http request methods, endponints, resources are if you are a beginner.

HTTP Request Methods, resources, API endpoints & Routing

Each and every time you send a request to a certain IP address using the browser, even though you don’t know , something called as an http request method is sent to the server. This http request method specifies what you(the client) wants to do with the resource at a certain endpoint. Okay so what’s a resource and an endpoint?

Lets understand this by a simple example:

Node.js Crash Course Tutorial #3 — Clients & Servers (NetNinja Youtube channel)

Imagine that you are logging into a certain website which serves static HTML pages. Once you log in, an http request method called a GET request is sent to the server specified on the URL. Since its a GET request, the server now knows that you are requesting for a certain resource which is an HTML page and responds with this resource being sent over to the client which is your browser(if it were another type of http request, the server provides a different response specified to the route). Then the HTML page is rendered on the browser. Lets see the most commonly used http request methods and the different types of requests they send to the server.

HTTP Request methods and the responses given to them by servers

  1. The GET method requests a representation of the specified resource from the server. Requests using GET should only retrieve data.

Now that we know what http request methods are, lets see what Routing means

Basic Routing and API endpoints

Routing refers to how the server we have created responds to the client requests( the requests sent from our browser to a particular destination). This particular destination is called as an API endpoint or also known as your application endpoint.

The above diagram shows few requests sent to the server with their respective paths or endpoints

Now that we have understood what http request methods, API endpoints & basics of routing are, lets see how we could create a route using Express.js

Basic Routing using Express.js

Lets see the structure of a route definition that we use in Express.js to respond to different routes.

app is the name we've given to the instance of express that we initialized.

METHOD is the http request method type. It can be a get, post, put, delete etc in lowercase.

PATH is the URL or Path that we want to target.

Handler is a function that gets executed if the route is matched. Therefore contains the logic to be executed once the route is matched

So far we have created an instance of express named app and the server is listening for requests on port 3000.

Now we need our server to respond to a get request from the client to the root URL or ‘/’ path. We use the route definition shown on our tutorial to get this done.

According to the above route definition, we could create a response to be sent to the browser as follows.

app.get('/', (req, res) =>{

res.send('Response to get request to path root URL')
}
)

In the handler function, we access both the request & response objects and send the response using it.

Lets see how we would add this on our code.

Now if we send a GET request to the root URL (‘/’), the server is supposed to respond us with the given string inside res.send() . Go to your browser and on the address bar, type localhost:3000/ and press enter.

And it works..!!!

By default the request made by the browser is a GET request, but if we want to send a different type of request , its not going to be easy to simulate other types of requests from the browser. So we are going to use the famous POSTMAN.

Go to Postman.com and install it on your device or you could use the Postman web app without installing it. I’m going to use the desktop application of Postman for this tutorial.

Following is the User Interface of the Postman application. As you can see you could send different types of http requests easily.

Full stack developer, Sitarist

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store