What Is REST API in Node.js?

Introduction

A REST API allows applications to communicate with each other over HTTP. For example, an Angular, React, or mobile application can use an API to retrieve users, create products, update records, or delete data from a server.

Node.js provides a JavaScript runtime for building backend applications, while Express.js simplifies routing and request handling. Together, they make it easier to create REST APIs that can be used by websites, mobile applications, and other services.

In this article, you will learn what a REST API is, how it works in Node.js, how to create one using Express.js, and the common mistakes developers should avoid.

What Is a REST API?

REST stands for Representational State Transfer. It is an architectural style for designing web services that communicate over HTTP.

An API (Application Programming Interface) allows different software applications to exchange information. A REST API follows REST principles and uses HTTP methods to work with resources.

For example, a frontend application can retrieve users by sending this request:


GET /api/users

The Node.js server processes the request and returns data, commonly in JSON format:


[
  {
    "id": 1,
    "name": "John",
    "email": "john@example.com"
  },
  {
    "id": 2,
    "name": "Sarah",
    "email": "sarah@example.com"
  }
]

The frontend can use this response to display users on a webpage.

Common HTTP Methods

Method Purpose Example
GET Retrieve resources /api/users
POST Create a resource /api/users
PUT Replace a resource /api/users/1
PATCH Partially update a resource /api/users/1
DELETE Request a resource. /api/users/1

Node.js can create APIs using its built-in HTTP module. However, Express.js provides convenient routing and middleware features that simplify development.

How Does a REST API Work in Node.js?

A REST API follows a client-server communication model:

  1. The client sends an HTTP request to an API endpoint.
  2. The Express.js server identifies the matching route.
  3. The server validates the request and performs the required operation.
  4. If necessary, the server retrieves or updates information in a database.
  5. The server returns a response with an HTTP status code and, commonly, JSON data.

For example, when a frontend sends GET /api/products, the server retrieves the products and returns them to the client.

A typical response might look like this:


{
  "success": true,
  "products": [
    {
      "id": 1,
      "name": "Laptop",
      "price": 60000
    }
  ]
}

REST APIs are generally stateless, meaning each request should contain the information needed to process it without depending on stored conversational state from previous requests.

Syntax

An Express.js route follows this syntax:


app.METHOD(PATH, HANDLER);

Here, METHOD specifies the HTTP method, PATH defines the endpoint, and HANDLER contains the function that processes the request.

For example:


app.get('/api/users', (req, res) => {
  res.json({ message: 'Users retrieved successfully' });
});

When a client sends a GET request to /api/users, Express.js executes the route handler and returns a JSON response.

Example: Create a REST API Using Node.js and Express.js

Let’s create a simple API to manage users.

Step 1: Create a Project

Create a project directory and initialize Node.js:


mkdir node-rest-api
cd node-rest-api
npm init -y

Step 2: Install Express.js

Run the following command:


npm install express

Step 3: Create the API

Create an app.js file and add the following code:


const express = require('express');
const app = express();

app.use(express.json());

let users = [
  { id: 1, name: 'John', email: 'john@example.com' },
  { id: 2, name: 'Sarah', email: 'sarah@example.com' }
];

// Get all users
app.get('/api/users', (req, res) => {
  res.json(users);
});

// Get a single user
app.get('/api/users/:id', (req, res) => {
  const user = users.find(
    user => user.id === Number(req.params.id)
  );

  if (!user) {
    return res.status(404).json({ message: 'User not found' });
  }

  res.json(user);
});

// Create a user
app.post('/api/users', (req, res) => {
  const { name, email } = req.body;

  if (!name || !email) {
    return res.status(400).json({
      message: 'Name and email are required'
    });
  }

  const newUser = {
    id: Math.max(0, ...users.map(user => user.id)) + 1,
    name,
    email
  };

  users.push(newUser);
  res.status(201).json(newUser);
});

// Update a user
app.put('/api/users/:id', (req, res) => {
  const user = users.find(
    user => user.id === Number(req.params.id)
  );

  if (!user) {
    return res.status(404).json({ message: 'User not found' });
  }

  const { name, email } = req.body;

  if (!name || !email) {
    return res.status(400).json({
      message: 'Name and email are required'
    });
  }

  user.name = name;
  user.email = email;

  res.json(user);
});

// Delete a user
app.delete('/api/users/:id', (req, res) => {
  const index = users.findIndex(
    user => user.id === Number(req.params.id)
  );

  if (index === -1) {
    return res.status(404).json({ message: 'User not found' });
  }

  users.splice(index, 1);
  res.status(204).end();
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Step 4: Run and Test the API

Start the server:


node app.js

The server runs at http://localhost:3000.

You can test the endpoints using Postman or another API client.

Operation Request
Get all users GET /api/users
Get one user GET /api/users/1
Create a user POST /api/users
Update a user PUT /api/users/1
Delete a user DELETE /api/users/1

For a POST request, send this JSON body:


{
  "name": "David",
  "email": "david@example.com"
}

The API returns the newly created user with status code 201.

This example stores users in an in-memory array. The data will reset when the server restarts. A production application should generally use a database such as MongoDB, MySQL, or PostgreSQL.

HTTP Status Codes in REST APIs

HTTP status codes indicate the result of a request.

Status Code Meaning
200 Request successful
201 Resource created
204 Successful request with no response body
400 PUT /api/users/1
401 Authentication required or failed
403 Access forbidden
404 Resource not found

For example, res.status(404).json({ message: ‘User not found’ }) informs the client that the requested user does not exist.

Real-Life Example

Consider an online shopping application. Its frontend may communicate with a Node.js backend to manage products.

  • GET /api/products retrieves the product list.
  • GET /api/products/10 retrieves a specific product.
  • POST /api/products creates a product.
  • PUT /api/products/10 updates a product.
  • DELETE /api/products/10 removes a product.

When a customer opens a product page, the frontend requests the product details from the API. The server retrieves the information from its database and returns a response.

The same API can serve a website, mobile application, or another authorized service.

Common Mistakes

  1. Using incorrect HTTP methods: Use GET to retrieve data and DELETE to remove resources instead of using GET for every operation.
  2. Using action-based URLs: Prefer /api/users with the appropriate HTTP method over endpoints such as /api/getUsers.
  3. Forgetting JSON middleware: Add app.use(express.json()) before routes that need to read JSON request bodies.
  4. Ignoring validation: Validate required fields, data types, and other input constraints before creating or updating resources.
  5. Returning incorrect status codes: Use suitable codes such as 201 for creation and 404 when a resource is missing.
  6. Exposing sensitive information: Never return passwords, private keys, or other confidential data in API responses.
  7. Ignoring error handling: Handle unexpected errors and return clear, consistent responses to clients.

Conclusion

A REST API allows applications to exchange data using HTTP methods and resource-based endpoints. Node.js provides the runtime for building backend APIs, while Express.js makes it easier to define routes, process requests, and return JSON responses.

By understanding HTTP methods, status codes, request handling, validation, and error handling, developers can build REST APIs for websites, mobile applications, and other services. Connecting these APIs to a database and adding appropriate security measures are important next steps when developing production applications.

What Is REST API in Node.js – Interview Questions

Q 1: What is a REST API?
Ans: A REST API is a web API that follows REST architectural principles and uses HTTP to access and manipulate resources.
Q 2: What does REST stand for?
Ans: REST stands for Representational State Transfer.
Q 3: What is a REST API in Node.js?
Ans: It is a backend API built with Node.js that allows clients to communicate with server-side resources through HTTP requests.
Q 4: What is the difference between PUT and PATCH?
Ans: PUT generally replaces a resource representation, while PATCH applies partial modifications.
Q 5: What is req.params in Express.js?
Ans: It contains route parameters. For /api/users/10, req.params.id contains the string "10".