How to create REST API in Node JS without using Express JS

How to create API in NodeJS without Express JS

Hello Friends 🙏, here I am with another 🔥 topic, how to create API in NodeJS without Express 😮😁.

Whenever we have to create API in Node, first thing we do is 😎 install Express JS, right!. Because it’s easy to write!, but under the hood it is using Node JS only, its just a wrapper.

Today in this Node JS Tutorial, we will create API in NodeJS without Express, will create POST & GET API and will learn how to use Postman to test API.👍.

Chalo suru kiya jaye!🍻 Lets start! 🕺.

Step 1: Install/Upgrade/Verify Node & Postman

To start with the setup, please verify if your machine has node. If not, then install node package here.

While upgrading node package on my machine to the latest version: 16.13.1 which includes npm 8.1.2, I faced one issue, maybe you also get this type of error, check here to resolve it: WARN npm does not support Node.js v16.13.1

Another tool you will need is Postman, this is needed to test API, as we are not developing front-end for now.

Step 2: Initialize a folder

So friends! first thing we have to do is to create a blank folder 📁 & initialize it using below command

npm init

This command will run a wizard of questions/choices related to the project & we have to answer/select them. This basically creates a package.json file which will include all our answers/selections.

node js,create api in nodejs without express,create post api in nodejs,create get api in nodejs,how to use postman to test api,nodejs tutorial

Step 3: Server Setup

Create server.js file, this will contain the code related to initialization of the server.

First import NodeJS http module, this allows NodeJS to transfer data over HTTP (Hyper Text Transfer Protocol).

// server.js file
const http = require("http");

Now we can create the server using http createServer method. It has two parameters:
request: this contains request Object from client
response: this contains response Object for client

Here we are just returning a string in response for client, so have used “Content-type”: “text/plain”.

const server = http.createServer((request, response) => {
  response.writeHead(200, { "Content-Type": "text/plain" });
  response.write("Hello World!");
  response.end();
});

Now lets bind this server to a port, so that server can receive requests. For this, we need to add a listener:

server.listen(9000, () => {
  console.log("Server is running on Port 9000");
});

That’s all, now to run the server open terminal/cmd prompt and run below command, this will run the server and start listening on port 9000.

node server.js
node js,create api in nodejs without express,create post api in nodejs,create get api in nodejs,how to use postman to test api,nodejs tutorial

Step 4: Use Postman to test API

Open Postman, enter the URL and click on Send button.
This will return the default mesage “Hello World!” from the server. 👏

node js,create api in nodejs without express,create post api in nodejs,create get api in nodejs,how to use postman to test api,nodejs tutorial

In this setup, server will return same message every time we hit URL from the Postman. And nothing will change if you make POST or a GET method.

Step 5: Server Setup for POST & GET API

Now to make this server setup ready for creating POST and GET API, we need to modify our server.js code, and instead of directly returning a response, we will check the method type and based on that, will code the logic (in controller.js).

Here we are fetching URL and Method type from the request parameter. And the switch statement depends upon the Method Type. We will be coding logic for each method type in next steps.
But first we have to declare default case, so that whenever we hit NodeJS server using Postman and if no case matches, then by default it will return “API not found” message.

// Update the Server Code
const server = http.createServer((request, response) => {
  const reqURL = request.url;
  const reqMethod = request.method;
  switch (reqMethod) {
    default: {
      defaultHandler(resquest, response)
    }
  }
});
// add defaultHandler method in controller.js
const defaultHandler = (request, response) => {
  response.writeHead(200, {
    "Content-Type": "application/json",
  });
  response.write(
    JSON.stringify({
      message: `API not found at ${request.url}`,
    })
  );
  response.end();
};

Now again access the API from postman and check the response.

node js,create api in nodejs without express,create post api in nodejs,create get api in nodejs,how to use postman to test api,nodejs tutorial

Create POST API in NodeJS

HTTP POST method is required to send data in the body of the API to the server.
As we will be sending data from Postman, this API must be able to read the data.
API name: post-api

// add POST case to the switch statement in server.js
case "POST": {
  if (reqURL === "/post-api") {
   postHandler(request, response);
  }
  break;
}
// add postHandler method in controller.js
export const postHandler = (request, response) => {
  //read the data from request
  response.writeHead(200, {
    "Content-Type": "application/json"
  });
  response.write(JSON.stringify({
    message: "POST Successful"
  }));
  response.end()
}

Now we have to parse the POST request body. In ExpressJS we use body-parser for the same.
But here we are using custom code, it will act as a body-parser to read the POST data.
I have created an another tutorial on this custom body parser, check here: How to parse the POST request body in NodeJS without using ExpressJS body-parser

// update the postHandler with custom body parser code
const postHandler = (request, response) => {

  let chunks = [];
  request.on("data", (chunk) => {
    chunks.push(chunk);
  });
  request.on("end", () => {
    const data = Buffer.concat(chunks);
    const parsedData = qs.parse(data.toString());
    console.log(parsedData);
    // Now request data is accessible using parsedData
    // And we can do any operation on the same, like saving it to databse

    //return the success response
    response.writeHead(200, {
      "Content-Type": "application/json",
    });
    response.write(
      JSON.stringify({
        message: "POST Succesfull",
      })
    );
    response.end();
  });
};

Now we can hit /post-api from Postman with some data.

node js,create api in nodejs without express,create post api in nodejs,create get api in nodejs,how to use postman to test api,nodejs tutorial

At server we will receive data as:

node js,create api in nodejs without express,create post api in nodejs,create get api in nodejs,how to use postman to test api,nodejs tutorial

Create GET API in NodeJS

HTTP GET method is required if we just want to request data and there is nothing to send. We can send, but in the form of querystring in the URL not in the body of the API.
API name: get-api

// add GET case to the switch statement in server.js
case "GET": {
  if (reqURL === "/get-api") {
   getHandler();
  }
  break;
}

Below in the controller, I have created a custom data Object, this will go back in response.

// add getHandler method in controller.js
const getHandler = (request, response) => {
  const data = {
    name: "frontendguruji",
    category: "technology",
    website: "frontendguruji.com",
  };
  response.writeHead(200, {
    "Content-Type": "application/json",
  });
  response.write(
    JSON.stringify({
      message: "GET Succesfull",
      data,
    })
  );
  response.end();
};

Now we can hit /get-api from Postman. Here we will receive the above custom data back in response from server.

node js,create api in nodejs without express,create post api in nodejs,create get api in nodejs,how to use postman to test api,nodejs tutorial

Checkout the project here.

Thats all in this NodeJS tutorial, here we learned how to create API in NodeJS without Express JS by setting up the server, implementing POST & GET API and learned how to use Postman to test API.
If you have any question or suggestion, please feel free to comment.

Thanks 🙏.

Leave a Comment

Your email address will not be published.