how to create REST API with nodejs

Nodejs is a popular choice for the backend as you can create REST API and consume it as you like from the client end. The built-in methods provided by nodejs are easy to use and understand for a beginner to get started. In this tutorial, we will see how you can create a basic REST API in nodejs. So, let us dig deeper!

Prerequisites

For this tutorial, you need is some basic knowledge of ES6. Other than this, you should have Nodejs installed on your PC or laptop and if you still have not done that yet you can get to our tutorial A beginner’s guide to NODEJS.

Creating a server

Now we will go through the whole process step by step so you can follow it easily without facing any difficulty.

Step 1

Create a new project folder with index.js file inside it. Navigate to the project folder and enter the following command in the command line.

npm init

Keep hitting enter through all the prompts. Once you pass through all the prompts, npm will set up your project with default settings. Author and description can always be edited later by going to the package.json and editing it. 

STEp 2

Now, let us start writing the code for our API. Open index.js and enter the following code inside it.

const http = require('http');
const port = 3000;
const hostname = '127.0.0.1';

const server = http.createServer((req,res)=>{
    res.statusCode = 200;
    res.setHeader('Content-Type','text/plain');
    res.write('Hello from nodejstutor\n');
    res.end()
});

server.listen(port,hostname,()=>{
    console.log(`Serving running at http://${hostname}:${port}/`);
});

To create a server, the createServer method from the HTTP module is used in the above code. We can add different header attributes of our choice along with the status codes. res.write() sends a basic text response to our client and the response ends with the res.end() method. To see the server running, enter the following command in the terminal.

node index.js

We will get the following output on the terminal.

Result

Let us move to the IP address provided to our server.listen() method.

http://127.0.0.1:3000/

createServer() function takes request and response as parameters for the server. In our code, we are sending “Hello from nodejstutor” as a response to our client i.e the browser.

Creating REST APIs.

Now that we have successfully made a basic server with a single endpoint, we will move to the more interesting part where we will be creating two different endpoints for the clients. Edit the index.js file and make sure it looks as follows.

const http = require("http")
const port = 3000
const hostname = "127.0.0.1"

const server = http.createServer((req,res) => {
    if(req.url === '/'){
res.statusCode = 200;
    res.setHeader('Content-Type','text/plain');
       res.write("Hello from nodejstutor")
       res.end() 
   }

    if(req.url === '/courses'){
       res.statusCode = 200;
       res.setHeader('Content-Type','text/plain');
       res.write("Welcome to courses")
       res.end()
    }
    if(req.url === '/homework'){
       res.statusCode = 200;
       res.setHeader('Content-Type','text/plain');
       res.write("We have your homework ready")
       res.end() 
    }

});


server.listen(port, hostname, () => {
  console.log(`Serving running at http://${hostname}:${port}/`)
})

Inside the createServer method, we are accessing the properties of the HTTP request that is made from the client-side. Req.url will give the part of URL after the domain name and we can return the appropriate responses based on them. In the above code, we have the default endpoint as http://127.0.0.1:3000/ along with the other two paths. Let us navigate to one of them and see the output on the browser screen.

Create REST API with nodejs
http://127.0.0.1:3000/courses

Voila! we have our desired output on the client side. Similarly, heading to http://127.0.0.1:3000/homework will return the text we are sending to the client.

Conclusion

In this tutorial, we have seen how you can successfully create REST API with nodejs by using the http module provided by it. This tutorial has the right information that you need to get as a beginner. There is a lot more you can do with nodejs that will be covered in the later articles.

Scroll to Top