How to create GET and POST endpoints in NodeJS using ExpressJS? (2024)

How to create GET and POST endpoints in NodeJS using ExpressJS? (2)

GET and POST endpoints are two of the most common endpoints in REST APIs. GET endpoints allow clients to retrieve data from the server, while POST endpoints allow clients to send data to the server. Here, I am going to show you how can we create essential GET and POST endpoints using NodeJS and ExpressJS.

We can use app.get() method to create a GET endpoint. This method is going to take two parameters, first is the path of endpoint and second is a callback function which will be executed every time the client makes a GET request to your endpoint.

Here’s an example of how we can create a GET endpoint at the path /users-list:

const express = require('express');

const app = express();

app.get('/users-list', (req, res) => {
// Get complete list of users
const usersList = [];

// Send the usersList as a response to the client
res.send(usersList);
});

Here’s an example of how we can use the above-created endpoint to make a GET request:

const fetch = require('fetch');

fetch('http://localhost:3000/users-list')
.then(response => response.json())
.then(usersList => {
console.log(usersList.data);
// Write an action that you want you want to perform with the response
})
.catch(error => {
console.log(error);
// Handle the error in case the request is not successfull
});

Below are the steps mentioned if you want to test this endpoint in Postman:

  1. Open Postman and create a new request.
  2. Set the HTTP method to GET.
  3. Set Url to http://localhost:3000/users-list.
  4. Send the request by clicking the Send button.

Sometimes we also need to send query parameters with a GET request so here’s a basic snippet to show that too:

const express = require('express');
const app = express();
app.get('/users-list/:id', (req, res) => {
const id = req.params.id;
// Get the user data from database
const user = {
id: 1,
name: 'John Doe',
};
// Send the response to the client
res.send({
user: user,
});
});

We can use the app.post() method to create a POST endpoint. This function also takes two parameters similar to app.get() the method. But here the callback has access to the request body i.e. the data sent by the client while making a request. We can use this endpoint to create new users.

Here’s an example of how we can create a POST endpoint at the path /users-list:

const express = require('express');

const app = express();

app.post('/users-list', (req, res) => {
const usersList = req.body;

// Save the data of user that was sent by the client

// Send a response to client that will show that the request was successfull.
res.send({
message: 'New user was added to the list',
});
});

Here’s an example of how we can use the above-created endpoint to make a POST request:

const fetch = require('fetch');

const user = {
name: "John Doe",
email: "[email protected]"
};

fetch('http://localhost:3000/users-list', {
method: 'POST',
body: JSON.stringify(user)
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});

Below are the steps mentioned if you want to test this endpoint in Postman:

  1. Open Postman and create a new request.
  2. Set the HTTP method to POST.
  3. Set the URL to http://localhost:3000/users-list.
  4. In the Body tab, set the content-type header to application/json.
  5. Then paste the JSON data in the body tab that you want to send.
  6. Send the request by clicking the Send button.

The examples given above are very basic and just for demo purposes. But you can follow the same steps to create more complex endpoints depending on your requirements.

Here are some additional tips that you can consider while creating any endpoint:

  • Use descriptive endpoint paths which will make a developer’s job to understand what actually your endpoint is doing
  • You can also validate the request body for your POST endpoints as an additional layer of check to ensure that the data you are receiving is in the correct format.
  • If possible, maintain thorough documentation that can easily describe your endpoint to any other developer on the team

I hope the above information was helpful to you. Thanks for reading it. If you have any questions, comments or concerns, do leave a comment below.

How to create GET and POST endpoints in NodeJS using ExpressJS? (2024)
Top Articles
Direct deposit: Questions Answered
How to Troubleshoot Slow Performance Issues
Cpmc Mission Bernal Campus & Orthopedic Institute Photos
Use Copilot in Microsoft Teams meetings
Places 5 Hours Away From Me
Amc Near My Location
Stretchmark Camouflage Highland Park
³µ¿Â«»ÍÀÇ Ã¢½ÃÀÚ À̸¸±¸ ¸íÀÎ, ¹Ì±¹ Ķ¸®Æ÷´Ï¾Æ ÁøÃâ - ¿ù°£ÆÄ¿öÄÚ¸®¾Æ
Chalupp's Pizza Taos Menu
Red Wing Care Guide | Fat Buddha Store
CHESAPEAKE WV :: Topix, Craigslist Replacement
Violent Night Showtimes Near Amc Fashion Valley 18
414-290-5379
Ktbs Payroll Login
Telegram Scat
Icommerce Agent
Aps Day Spa Evesham
Walmart Car Department Phone Number
Riherds Ky Scoreboard
Joan M. Wallace - Baker Swan Funeral Home
Southland Goldendoodles
January 8 Jesus Calling
208000 Yen To Usd
Giantbodybuilder.com
Pulitzer And Tony Winning Play About A Mathematical Genius Crossword
Weather Underground Durham
Viduthalai Movie Download
R/Mp5
Ellafeet.official
Kstate Qualtrics
Lake Dunson Robertson Funeral Home Lagrange Georgia Obituary
Goodwill Houston Select Stores Photos
The Best Carry-On Suitcases 2024, Tested and Reviewed by Travel Editors | SmarterTravel
Craigslist Greencastle
Petsmart Northridge Photos
Hingham Police Scanner Wicked Local
Craigslist - Pets for Sale or Adoption in Hawley, PA
Emily Browning Fansite
Mathews Vertix Mod Chart
Enr 2100
Samsung 9C8
Random Warzone 2 Loadout Generator
Craigslist Marshfield Mo
Online TikTok Voice Generator | Accurate & Realistic
Publix Store 840
Helpers Needed At Once Bug Fables
David Turner Evangelist Net Worth
Tamilyogi Cc
Used Curio Cabinets For Sale Near Me
Palmyra Authentic Mediterranean Cuisine مطعم أبو سمرة
32 Easy Recipes That Start with Frozen Berries
Latest Posts
Article information

Author: Msgr. Refugio Daniel

Last Updated:

Views: 6373

Rating: 4.3 / 5 (54 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Msgr. Refugio Daniel

Birthday: 1999-09-15

Address: 8416 Beatty Center, Derekfort, VA 72092-0500

Phone: +6838967160603

Job: Mining Executive

Hobby: Woodworking, Knitting, Fishing, Coffee roasting, Kayaking, Horseback riding, Kite flying

Introduction: My name is Msgr. Refugio Daniel, I am a fine, precious, encouraging, calm, glamorous, vivacious, friendly person who loves writing and wants to share my knowledge and understanding with you.