NodeJS | Building simple REST API in express

Let’s have a brief introduction about the Express framework before starting the code section:

Express: It is an open source NodeJs web application framework designed to develop websites, web applications and APIs in a pretty easier way.
Express helps us to handle different HTTP requests at specific routes.

As it is NodeJs web framework so make sure that NodeJs has been installed at our system.

For verifying type following command in the terminal:

node -v

It will show the installed version of NodeJs to our system as shown in the below screenshot.

    Steps to be performed for building a simple REST API:

  • STEP-1:
    Create a separate folder and with the help of terminal or command prompt navigate to this folder:
  • STEP-2:
    Create package.json by typing following command in the terminal:

    npm init -y

    For knowing more about package.json click here.

  • STEP-3:
    Create a file named server.js at the root of the project.
    Now, our folder structure will be as shown in the screenshot below:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // server.js File
    const express = require('express'); // Importing express module
      
    const app = express(); // Creating an express object
      
    const port = 8000;  // Setting an port for this application
      
      
    // Starting server using listen function
    app.listen(port, function (err) {
       if(err){
           console.log("Error while starting server");
       }
       else{
           console.log("Server has been started at "+port);
       }
    })

    chevron_right

    
    

  • STEP-4:
    Start server by typing following command in the terminal:

    node server.js
  • STEP-5:
    Open the browser and type http://localhost:8000 and we will get the following response.

    We are getting Cannot GET / response as we are trying to access/route to the server and there is nothing mounted to that particular route.

  • STEP-6: Handing the route to server
    Handle the root route of the server by sending something back to it and adding the following code to the server.js

    app.get('/', function (req, res) {
      res.send('we are at the root route of our server');
    })
    

    Now, restart the server by typing following command :

    node server.js
  • Source code explanation:

    By using this line of code we are importing the Express package.

    const express = require('express'); // Importing express package


    By using this line of code we are creating an Express object, this object instance will be stored in app variable and then functions will be called over this object.

    const app = express(); // Creating an object
    const port = 8000;  // Defining port to 8000


    By using these lines we are listening server at port number 8000. Here the first parameter is port and the second parameter is a function for handling the error.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    app.listen(port, function(err){
    if(err){
    console.log("Error while starting server");
    }
    else{
    console.log("Server has been started at "+port");
    }
    })

    chevron_right

    
    


    By using these lines we are handing root route of the server and sending a GET request to it with a specific message.

    app.get('/', function(req, res){
    res.send('We are at the root route of our server');
    })
    

    Complete code for REST API is as:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    const express = require('express');
      
    const app = express();
    const port = 8000;
      
    app.listen(port, function (err) {
        if(err){
            console.log("error while starting server");
        }
        else{
            console.log("server has been started at "+port);
        }
    })
      
    app.get('/', function (req, res) {
       res.send('we are at the root route of our server');
    })

    chevron_right

    
    

    In this way, we can create a simple server using the Express web framework.



    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




    Article Tags :

    4


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.