Create Backend

REST API using Express.js

For detailed description:

https://expressjs.com/en/starter/installing.html

  1. Create packge.json

    npm init
    
  2. Create Entry Point file server.js

  3. Create HTTP Server in server.js → Use express

    npm install express
    
  4. Create requests.http and write the server requests there and click on send request

    get <http://localhost:4000/users>
    
  5. Add API Routing

    Syntax: app.METHOD ( path , request handler )

    app.get('/users', (req, res) => {
        res.send({message: 'All Users'});
    });
    
  6. Parametrized Request

    1. This route handles GET requests to /users/:id, where :id is a dynamic parameter representing the user ID.
    2. If the user is found, it sends a JSON response with the user data; if not, it sends a 'User not found' message.
    3. Making Request → get http://localhost:4000/users/1
    // Send 1 user by id
    app.get('/users/:id', (req, res) => {
        const userId = Number(req.params.id);
        //  Search user by id in usersList array 
        let userById = usersList.find(user=>user.id==userId);
        if(userById === undefined){
            res.send({message: 'User not found'});
        }
        else{
            res.send({message: 'User by Id', payload: userById});
        }
    });
    

Making HTTP requests

For initial learning stages , we use a pseudo Client side application called REST Client.

Postman can also be used for testing the REST API.

REST Client

Installation

VS Marketplace Link: https://marketplace.visualstudio.com/items?itemName=humao.rest-client

Usage:

  1. Create a file names requests.http in folder of server.