GET Call using ExpressJS

share link

by Abdul Rawoof A R dot icon Updated: Jan 26, 2024

technology logo
technology logo

Guide Kit Guide Kit  

A GET request is a way to seize data from a data source using the internet. It's finished. The use of the GET request method is common.

It's like POST, PUT, or DELETE. Despite the capitalization, “GET” isn't an acronym, so it would not stand for anything. GET requests are the most common strategy in APIs and websites. They are also the most used. Simply put, you use the GET method to retrieve data from a server at the specified resource.

For example, say you've got got an API with a /customers endpoint. Making a GET request to that endpoint have to go back a listing of all to be had users. We have two common methods for the request and response between a server and a client. The first is GET. It requests data from a specified resource. The second is POST. It submits processed data to a specified resource. When we interact with a web server, POST requests place user parameters in the body of the HTTP request. In contrast, 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. Open 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(express.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.

FAQ

1. What is a GET request?

Making a GET request is like asking a server for information. It's a common way to get data from a specific place on the internet.


2. How is GET different from other methods?

GET is like asking for information, while POST, PUT, and DELETE are more about sending or changing data. GET is like reading, others are like writing or deleting.


3. Where do we use GET requests?

You use GET when you want to fetch data from a web server. For example, getting a list of users from an API's /users page.


4. Can you give an example of a GET request?

Sure! Imagine you want information about cats from a website. Making a GET request is like typing the question in your browser and getting a page with cat info.


5. How is GET different from POST in simple terms?

Think of GET as asking for information by reading the URL, like browsing a webpage. But, POST is like submitting or sending data. It usually happens behind the scenes when you fill out a form online.

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.