How To Create POST Request API with Node.js

How To Create POST Request API with Node.js
362 Views

Creating a POST request API in Node.js using the Express framework is a foundational skill for backend developers. This guide, proudly presented by CodexCoach, will not only serve as a node js express API example but will also take you through the process step by step.

By the end, you’ll have mastered how to create a post API in node js, equipped with knowledge to test your APIs with tools like Postman.

1. Introduction

Node.js and Express framework collectively offer a robust environment for building scalable and efficient web applications, especially when it comes to RESTful APIs.

This guide focuses on how to create a post API in Node.js, providing a clear node js express rest api example for developers to use as a blueprint for their projects. Our discussion will exemplify the simplicity and power of developing REST APIs with Node.js and Express.

2. Install Library in Project

Setting up your project environment is the first step towards building your post request API Node js application. Assuming Node.js is installed on your system, you will begin by setting up a new project directory and initializing a Node.js project.

mkdir myproject
cd myproject
npm init -y

Next, install Express, the de facto library for handling HTTP requests in Node.js applications.

npm install express dotenv nodemon

3. Create server.js File

Now, let’s create the server.js file, which will be the entry point of our application. In this file, you’ll define the Express application and the POST request endpoint.

// Express.js Application for managing user data
const express = require("express");
const app = express();


// DOTENV TO SECURE SECRET DATA
require("dotenv").config();
app.use(express.json());


// PORT FOR START SERVER
const port = process.env.PORT || 3000;


/*-----------------------------------------------------------------------------------*/
// Assuming 'app' is an instance of Express
app.post("/sum", (req, res) => {
 const num1 = parseFloat(req.body.number1); // Parse the numbers to ensure they are treated as numbers
 const num2 = parseFloat(req.body.number2);
 const sign = req.body.sign;


 let sum;


 switch (sign) {
   case "+":
     sum = num1 + num2;
     break;
   case "-":
     sum = num1 - num2;
     break;
   case "*":
     sum = num1 * num2;
     break;
   case "/":
     sum = num1 / num2;
     break;
   default:
     return res.status(400).json({ result: false, message: "Invalid sign" });
 }


 res
   .status(200)
   .json({ result: true, answer: sum, message: `Your answer is ${sum}` });
});


/*-----------------------------------------------------------------------------------*/
// Start the server
app.listen(port, () =>
 console.log(`Example app listening at http://localhost:${port}`)
);

In this simple node js express rest api example, we’ve created an API endpoint that listens for POST requests on /api/resource. It uses the express.json() middleware to automatically parse JSON request bodies, making the incoming data easy to work with.

4. Download Demo from Here

To help you get started quickly, CodexCoach provides a downloadable demo of this project. Download the complete project here to explore the code in detail and experiment with it on your own.

This demo serves as a practical node js express api example, illustrating the setup and configuration needed for a basic POST request API.

5. How to Run POST Request API in Postman or Else Application

Testing your API is a crucial part of the development process. Postman is a popular tool for testing APIs, allowing you to send requests to your server and view the responses. Here’s how to test the POST request API we’ve just created:

  • Open Postman and create a new request.
  • Set the request type to POST and enter the URL of your API endpoint (e.g., http://localhost:3000/sum).
  • In the ‘Body’ tab, select ‘raw’ and choose ‘JSON’ as the format. Enter the JSON object you want to send in the request body.
Method :- post,
Api :- http://localhost:3000/sum,
Data request Raw JSON = {
"number1": 5,   
"sign": "*",   
"number2": 6
}
  • Hit ‘Send’ to execute the request and view the response from your server.

This process demonstrates how to interact with your REST API, providing a clear example of how to run a post request API in Node.js using tools like Postman.

Also read:

How To connect mongoDB database with Node js

How To connect mySQL database with Node js

How To create AddToCart In Next Js & React js

Was this article helpful?
YesNo

Leave a comment

Your email address will not be published. Required fields are marked *