Get call using ExpressJS

share link

by Abdul Rawoof A R dot icon Updated: Mar 21, 2023

technology logo
technology logo

Guide Kit Guide Kit  

A GET request, in simple terms, is a way for you to grab data from a data source with the help of the internet. It's done using the GET request method, which is a very common HTTP request method (like POST, PUT, or DELETE). Despite the capitalization, “GET” is not an acronym, so it doesn't stand for anything.


GET requests are the most common and widely used methods in APIs and websites. Simply put, the GET method is used to retreive data from a server at the specified resource. For example, say you have an API with a /users endpoint. Making a GET request to that endpoint should return a list of all available users. We have two common methods for the request and response between a server and client that are, GET-it requests the data from a specified resource and POST-it submits the processed data to a specified resource. When we are interacting with a web server POST requests place user parameters in the body of the HTTP request and on the other hand, GET requests place such parameters in the URL.


Here is an example of how to implement GET call using ExpressJS:

Fig: Preview of the output that you will get on running this code from your IDE.

Code

const express = require('express');
const app = express();

// require body parser middleware
const bodyParser = require('body-parser')

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

//Create user data.
const userData = [
    {
        id: 673630,
        firstName: 'Prasanta',
        lastName: 'Banerjee',
        age: 24,
        hobby: [
            {
                coding: ['java', 'python', 'javascript'],
                movies: ['action', 'comedy', 'suspense'],
                sports: "basketball"
            }
        ],
        oper_sys: ['Mac', 'Windows']
    },
    {
        id: 673631,
        firstName: 'Neha',
        lastName: 'Bharti',
        age: 23
    },
    {
        id: 673651,
        firstName: 'Priyanka',
        lastName: 'Moharana',
        age: 24
    },
    {
        id: 673649,
        firstName: 'Shreyanshu',
        lastName: 'Jena',
        age: 25
    },
    {
        id: 673632,
        firstName: 'Priyanka',
        lastName: 'Sonalia',
        age: 23
    },
    {
        id: 673653,
        firstName: 'Bhupinder',
        lastName: 'Singh',
        age: 25
    },
];

//Create the API endpoints with callback functions.
//Display all Employees data.
app.get('/api/employees', function (req, res) {
    res.json(userData);
});

//Display employee data based on 'id' param.
app.get('/api/employees/:id', function (req, res) {
    const id = req.params.id;
    const user = userData.find(user => user.id == id)

    if (user) {
        res.statusCode = 200
        res.json(user)
    }
    else {
        res.statusCode = 404
        return res.json({ Error: ['ID Not Found'] });
    }
});

// POST emplyee data
app.post('/api/employees/', function (req, res) {

    // catch request body data, break it down and assign it to a variable
    // you can just parse req.body as well
    const newUser = {
        id: req.body.id,
        firstName: req.body.firstName,
        lastName: req.body.lastName
    }

    userData.push(newUser);
    res.status(200).json(newUser);
});

//start the node server.
const PORT = 7777;
app.listen(PORT, function () {
    console.log('Your server is up & running at localhost:' + PORT + '. Please hit the APIs.');
});

Instructions

Follow the steps carefully to get the output easily.

  1. Install Visual Studio Code on your computer.
  2. Install - npm init --yes(to install json package file).
  3. Install - npm install --save express.
  4. Create a new JS file.
  5. Copy the snippet using the 'Copy' button and paste it into that JS file.
  6. Save the file and open the terminal, using 'node filename(node.js) to get the output.
  7. Then, open the Postman tool and copy the API and port address in the code then paste it into the URL box and send the request.


I hope you found this helpful.


I found this code snippet by searching for 'post calls using expressjs' in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created and tested in Visual Studio Code 1.74.1.
  2. ExpressJS version - 1.0.0.


Using this solution, we are able to implement GET call using ExpressJS with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to to implement GET call using ExpressJS.

Support

  1. For any support on kandi solution kits, please use the chat
  2. For further learning resources, visit the Open Weaver Community learning page.