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
U.S. Visitor Information
Single Withholding vs. Married Withholding: What’s the Difference?
Splunk Stats Count By Hour
Team 1 Elite Club Invite
Athletic Squad With Poles Crossword
41 annonces BMW Z3 occasion - ParuVendu.fr
Cube Combination Wiki Roblox
Nonuclub
Bjork & Zhulkie Funeral Home Obituaries
Busty Bruce Lee
Think Up Elar Level 5 Answer Key Pdf
Void Touched Curio
Nalley Tartar Sauce
Gdp E124
Trac Cbna
Rams vs. Lions highlights: Detroit defeats Los Angeles 26-20 in overtime thriller
Craighead County Sheriff's Department
Www Craigslist Milwaukee Wi
Tamilyogi Proxy
Van Buren County Arrests.org
Dallas Craigslist Org Dallas
Quadcitiesdaily
Drift Boss 911
Rust Belt Revival Auctions
Craigs List Jonesboro Ar
Urban Dictionary Fov
A Christmas Horse - Alison Senxation
Bleacher Report Philadelphia Flyers
Ticket To Paradise Showtimes Near Cinemark Mall Del Norte
Miller Plonka Obituaries
UAE 2023 F&B Data Insights: Restaurant Population and Traffic Data
Www Mydocbill Rada
James Ingram | Biography, Songs, Hits, & Cause of Death
3 Bedroom 1 Bath House For Sale
Rvtrader Com Florida
Nina Flowers
Weekly Math Review Q2 7 Answer Key
Anderson Tribute Center Hood River
Hkx File Compatibility Check Skyrim/Sse
Citymd West 146Th Urgent Care - Nyc Photos
Squalicum Family Medicine
Holzer Athena Portal
La Qua Brothers Funeral Home
The Average Amount of Calories in a Poke Bowl | Grubby's Poke
Msatlantathickdream
Sleep Outfitters Springhurst
Electric Toothbrush Feature Crossword
Jovan Pulitzer Telegram
8663831604
Famous Dave's BBQ Catering, BBQ Catering Packages, Handcrafted Catering, Famous Dave's | Famous Dave's BBQ Restaurant
Lux Nails & Spa
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.