NodeJS is most commonly used with Express framework

NodeJS is most commonly used with Express framework. Also a bunch of other external libraries are used with NodeJS.

NodeJS is most commonly used with Express framework. Also a bunch of other external libraries are used with NodeJS.

The Reason these frameworks and libraries are used along with NodeJS is to make development much more easier and quicker.

While working on any real project, it is best to use frameworks and libraries wherever needed to enable quicker development 😄

That said, in this post I will be showing how to build Simple REST API’s with NodeJS without using express framework or any other external libraries. This article will use only those functionalities that are provided with NodeJS itself.

The reason for this is to show how NodeJS can be used without frameworks and libraries as well 😄. Also this will give a better idea as to how NodeJS works

Pre-requisite

Code

Let’s get started with the code

Create a folder called as simple-rest-apis-nodejs-without-frameworks. This will be our NodeJS Project folder.

Go into the project folder and use npm init to make the project into a node project. The commands to do this are

cd simple-rest-apis-nodejs-without-frameworksnpm init

package.json

After running npm init a package.json file is created within the project folder.

package.json has information about your project like project name, version, description etc. Also package.json is where you will be adding node dependencies. In this article we won’t be having any dependencies since we are using only functionalities that are provided by NodeJS itself.

First API

Create a file called server.js inside the project folder. This will be the starting point of our application.

This code checks if the request URL has a query parameter called as name and stores it in name variable. If no query parameter is present, it defaults to the string World

The response status is set as 200, Content Type of the response is JSON and finally the response is sent back using res.end(JSON.stringify(response));

since response variable is a JSON Object, we are using JSON.stringify on it to convert it to string before sending back the http response

Now we can run the application using the command

nodeserver.js

Testing

In order to test the endpoint use postman. You can download it from here

In postman select Get request and type the url as http://localhost:3000/sample?name=aditya and hit send

The output for this request is shown below

{ "text": "Hello aditya"}

Now type the url as http://localhost:3000/sample and hit send

The output for this request is shown below

{ "text": "Hello World"}

Second API

In this section we will be building the second API which is a POST request. Also if user hits some random url, we will need to indicate that it is an invalid route. We will add the logic for that as well here.