What is REST API in NodeJS?
Last Updated :
17 Mar, 2025
NodeJS is an ideal choice for developers who aim to build fast and efficient web applications with RESTful APIs. It is widely adopted in web development due to its non-blocking, event-driven architecture, making it suitable for handling numerous simultaneous requests efficiently.
But what makes NodeJS such a popular tool for building REST APIs? Why should developers consider using it, and what is the best way to get started? In this article, we will explore the fundamentals of REST APIs in NodeJS, including how to set up a server, define routes, process requests and responses, and interact with databases.
What is REST API?
A REST (REpresentational State Transfer) API is a web service that follows the principles of REST architecture to interact between clients and servers over HTTP. It uses standard HTTP methods (GET, POST, PUT, DELETE) to perform CRUD (Create, Read, Update, Delete) operations on resources, and data is typically transferred in JSON or XML format.
Principles of REST API
REST APIs are built on six fundamental principles that define their architecture and functionality:
- Statelessness: Each request from a client to the server must contain all the necessary information, and the server does not store session-related data.
- Client-Server Architecture: The client and server are separate entities, allowing for independent development and scalability.
- Uniform Interface: A consistent way of accessing resources, typically via standardized HTTP methods (GET, POST, PUT, DELETE).
- Cacheability: Responses from the server should indicate whether they can be cached to improve performance.
- Layered System: The architecture should support multiple layers (such as load balancers, authentication servers, and data storage) without affecting the client-server interaction.
- Code on Demand (Optional): The server can send executable code (like JavaScript) to the client to enhance functionality, though this is rarely used.
HTTP Methods Used in API
In RESTful APIs, HTTP methods define the actions to be performed on resources. Each HTTP method corresponds to a specific operation in the CRUD (Create, Read, Update, Delete) cycle. Here’s an explanation of the commonly used HTTP methods:
GET Method
The GET method is used to retrieve an existing resource from the server. The server responds with the resource's data, often in JSON or XML format. It is used to read the data.
HTTP GET http://example.com/users
HTTP GET http://example.com/users/123
POST Method
The POST method is used to create a new resource on the server. It sends data to the server as part of the request body, typically in JSON or XML format. It is used to create a new resource on the server.
HTTP POST http://example.com/users
HTTP POST http://example.com/users/123
PUT Method
The PUT method is used to update an existing resource on the server. It requires the client to send the updated data in the request body. It is used to update the data.
HTTP PUT http://example.com/users/123
HTTP PUT http://example.com/users/123/name/Anjali
PATCH Method
The PATCH method is used to apply partial modifications to a resource. Unlike PUT, which typically updates the entire resource, PATCH only sends the changes to be made, making it more efficient in certain scenarios. It is used to partially update the data on the server.
HTTP PATCH http://example.com/users/123
HTTP PATCH http://example.com/users/123/name/Anjali
DELETE Method
The DELETE method is used to delete a resource from the server. Once executed successfully, it usually returns a status code indicating the deletion has been completed, such as 200 OK or 204 No Content. It is used to delete the data.
HTTP DELETE http://example.com/users/123
HTTP DELETE http://example.com/users/123/name/Ravi
How to Create a REST API in NodeJS?
You can create a simple REST API in NodeJS using the built-in http module or the more popular Express.js framework, which simplifies routing and middleware handling.
Step 1: Create the folder
Create the NodeJs project by using the following command
mkdir node-app
cd node-app
Step 2: Install the package.json
npm init -y
Step 3: Install Express
To begin building a REST API in NodeJS, you need to install Express. Run the following command in your terminal:
npm install express
Step 4: Create the Server
Here’s a basic example of creating a REST API in NodeJS using Express
JavaScript
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
app.get('/users', (req, res) => {
res.json({ message: 'Returning list of users' });
});
app.post('/users', (req, res) => {
const newUser = req.body;
res.json({ message: 'User created', user: newUser });
});
app.put('/users/:id', (req, res) => {
const userId = req.params.id;
const updatedUser = req.body;
res.json({ message: `User with ID ${userId} updated`, updatedUser });
});
app.delete('/users/:id', (req, res) => {
const userId = req.params.id;
res.json({ message: `User with ID ${userId} deleted` });
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Output:
Run the server
node app.js
Open the http://localhost:3000 on the postman to check the API is working properly or not.
In this example
- GET /users: This route fetches the list of users (or mock data in this case).
- POST /users: This route accepts JSON data from the client to create a new user.
- PUT /users/:id: This route updates the information of a user based on the user ID provided in the URL.
- DELETE /users/:id: This route deletes a user with the specified ID.
Common HTTP Status Codes in REST APIs
When working with REST APIs, you’ll often encounter the following HTTP status codes that indicate the result of the request:
- 200 OK: The request was successful, and the server returned the requested data.
- 201 Created: A new resource has been successfully created (usually returned for POST requests).
- 400 Bad Request: The request is malformed or missing required data.
- 401 Unauthorized: The request requires authentication, and the user is not authorized.
- 404 Not Found: The requested resource was not found.
- 500 Internal Server Error: The server encountered an unexpected condition.
Best Practices for Building REST APIs in NodeJS
- Use HTTP Status Codes Properly: Always return the correct status code to indicate the result of the request.
- Keep Routes Consistent: Use consistent naming conventions and URL patterns to make your API intuitive and easy to use.
- Use Middleware for Error Handling: Add middleware functions to handle errors globally across all routes.
- Secure Your API: Use authentication mechanisms like JWT (JSON Web Tokens) to ensure that only authorized users can access certain endpoints.
- Validate Input: Always validate incoming data to prevent issues and ensure that the data adheres to the required structure.
- Use Caching: Consider caching responses for frequently requested resources to improve performance and reduce server load.
Similar Reads
What is Node? Node is a JavaScript runtime environment that enables the execution of code on the server side. It allows developers to execute JavaScript code outside of a web browser, enabling the development of scalable and efficient network applications. Table of Content What is Node?Steps to setup the Node App
3 min read
RESTful Routes in Node.js Routing: Routing is one of the most significant parts of your website or web application. Routing in Express is basic, adaptable, and robust. Routing is the mechanism by which requests (as specified by a URL and HTTP method) are routed(directed) to the code that handles them. Â What is RESTful Routin
4 min read
What is Middleware in Express.js ? Middleware functions have access to the request object and the response object and also the next function in the application request-response lifecycle. Middlewares are used for: Change the request or response object.Execute any program or codeEnd the request-response lifecycleCall the next middlewa
2 min read
How to make HTTP requests in Node ? In the world of REST API, making HTTP requests is the core functionality of modern technology. Many developers learn it when they land in a new environment. Various open-source libraries including NodeJS built-in HTTP and HTTPS modules can be used to make network requests from NodeJS.There are many
4 min read
Types of API functions in Node.js Node.js, known for its asynchronous and event-driven architecture, is a popular choice for building scalable server-side applications. One of its primary uses is to create and manage APIs (Application Programming Interfaces). APIs allow different software systems to communicate and share data with e
6 min read
Getting Started with NodeJS Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside of a browser. It is built on Chrome's V8 JavaScript engine. It is also event-driven means it can handle multiple requests at the same time without blocking. By using Node.js, we can create
5 min read
What Is Axios? Axios is a popular open-source JavaScript library used to make HTTP requests from web browsers or Node.js environments. It simplifies the process of sending asynchronous HTTP requests to REST endpoints, handling responses, and performing various network-related tasks. Built on top of JavaScriptâs na
5 min read
Routing in NodeJS Routing is the process of deciding how a server should respond to different requests made by users. When you visit a website or use an app, your browser sends a request to the server. Routing determines how the server handles these requests based on the URL you visit and the type of request (such as
3 min read
What is the use of the Fetch API in JavaScript ? The Fetch API in JavaScript provides a modern, powerful, and flexible way to make HTTP requests from web browsers or Node.js environments. Its primary purpose is to facilitate fetching resources, typically data, from servers or other sources across the web. In simple terms, the Fetch API in JavaScri
2 min read
How HTTP POST requests work in Node ? The HTTP POST method is used to send data from the client to the server. Unlike GET, which appends data in the URL, POST sends data in the request body, which makes it ideal for form submissions, file uploads, and secure data transfers.In Node.js, handling POST requests is commonly done using the Ex
2 min read