Examples


Express.js - REST API


A REST API (Representational State Transfer Application Programming Interface) in Express.js is a way to build web services that allow clients (such as web or mobile apps) to communicate with a server using HTTP methods like GET, POST, PUT, and DELETE.

Key Features of REST API in Express.js

  • Stateless : Each request from a client contains all the information needed, with no session stored on the server.
  • Uses HTTP Methods
    • GET → Retrieve data
    • POST → Create new data
    • PUT → Update existing data
    • DELETE → Remove data
  • Follows REST Principles : Uses URLs as resources (e.g., /users to manage users).
  • Returns Data in JSON Format : Standard for APIs, making it easy for clients to consume.

Install Dependencies

Install Express.js with the npm command.

npm install express

Basic Express.js REST API Setup

  • This Express.js app provides a simple REST API for managing users using standard CRUD operations (GET, POST, PUT, DELETE).
  • Responses include HTTP status codes and structured JSON messages to indicate success or failure.

Create a file index.js and set up a simple API

index.js
const express = require('express');
const app = express();

app.use(express.json());

// Sample data
let users = [
  { id: 1, name: "Sam", email: "sam@gmail.com" },
  { id: 2, name: "Ram", email: "ram@gmail.com" },
];

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

// GET a user by ID
app.get('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (user) {
    res.status(200).json({
      message: 'User retrieved successfully',
      user,
    });
  } else {
    res.status(404).json({
      message: 'User not found',
    });
  }
});

// POST (create) a new user
app.post('/users', (req, res) => {
  const newUser = {
    id: users.length + 1,
    name: req.body.name,
  };
  users.push(newUser);
  res.status(201).json({
    message: 'User created successfully',
    user: newUser,
  });
});

// PUT (update) a user
app.put('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (user) {
    user.name = req.body.name;
    res.status(200).json({
      message: 'User updated successfully',
      user,
    });
  } else {
    res.status(404).json({
      message: 'User not found',
    });
  }
});

// DELETE a user
app.delete('/users/:id', (req, res) => {
  const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
  if (userIndex !== -1) {
    users.splice(userIndex, 1);
    res.status(200).json({
      message: 'User deleted successfully',
    });
  } else {
    res.status(404).json({
      message: 'User not found',
    });
  }
});

// Start Server
const PORT = 5000;

app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`);
});

Run the Server

Run the server using the command is given below.

node index.js
D:\my-app>node index.js
Server running at http://localhost:5000

Output

Get All Users
Request:
GET: http://localhost:5000/users
Content-Type: application/json
      
Response:
Status: 200 OK
Content-Type: application/json

{
  "message": "Users retrieved successfully",
  "data": [
    { 
        "id": 1, 
        "name": "Sam", 
        "email": "sam@gmail.com" 
    },
    { 
        "id": 2, 
        "name": "Ram", 
        "email": "ram@gmail.com" 
    }
  ]
}
      
Get User by ID
Request:
GET: http://localhost:5000/users/1
Content-Type: application/json
      
Response:
Status: 200 OK
Content-Type: application/json

{
  "message": "User retrieved successfully",
  "data": {
    "id": 1,
    "name": "Sam",
    "email": "sam@gmail.com"
  }
}
      
Create New User
Request: 
POST: http://localhost:5000/users
Content-Type: application/json

{
  "name": "Alex",
  "email": "alex123@gmail.com"
}
      
Response:
Status: 201 Created
Content-Type: application/json

{
  "message": "User created successfully",
  "data": {
    "id": 3,
    "name": "Alex",
    "email": "alex123@gmail.com"
  }
}
      
Update User
Request:
PUT: http://localhost:5000/users/2
Content-Type: application/json

{
  "name": "Ram Kumar",
  "email": "ramkumar12@gmail.com"
}
      
Response:
Status: 200 OK
Content-Type: application/json

{
  "message": "User updated successfully",
  "data": {
    "id": 2,
    "name": "Ram Kumar",
    "email": "ramkumar12@gmail.com"
  }
}
      
Delete User
Request:
DELETE: http://localhost:5000/users/3
Content-Type: application/json
      
Response:
Status: 200 OK
Content-Type: application/json

{
  "message": "User deleted successfully"
}