Express.js is a lightweight web framework for Node.js that simplifies the creation of RESTful APIs. A REST API allows applications to exchange data efficiently using HTTP methods such as GET, POST, PUT, and DELETE. In this tutorial, you will build a REST API to perform basic CRUD operations on user data.



Setting Up the Project

To begin, create a new project directory and initialize it using npm.

// Create project directory
mkdir express-rest-api
cd express-rest-api

// Initialize npm project
npm init -y

// Install Express.js
npm install express

Creating the Basic API Structure

Set up a basic server in a file named server.js:

// Import the Express module
const express = require('express');
const app = express();
const port = 3000;

// Middleware to parse incoming JSON requests
app.use(express.json());

// Root route
app.get('/', (req, res) => {
    res.send('Welcome to the Express REST API');
});

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

Run the server with:

node server.js

Visit http://localhost:3000 to ensure that the server is running.

Creating the In-Memory User Database

For simplicity, we will use an in-memory database to store user information:

// Sample user data (in-memory database)
let users = [
  { id: 1, name: 'Rahul Sharma', email: '[email protected]' },
  { id: 2, name: 'Demo User', email: '[email protected]' }
];

Implementing RESTful Routes

To build a complete REST API, you need to define routes that handle the following HTTP methods:

  1. POST: Create a new user.
  2. GET: Retrieve all users or a specific user.
  3. PUT: Update user details.
  4. DELETE: Remove a user.

Create User (POST Request)

Add a route to create a new user:

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

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

  // Generate a unique ID for the new user
  const newId = users.length > 0 ? Math.max(...users.map(user => user.id)) + 1 : 1;

  const newUser = {
    id: newId,
    name,
    email
  };

  // Add the new user to the in-memory database
  users.push(newUser);

  res.status(201).json({ message: 'User created successfully', newUser });
});

Retrieve All Users (GET Request)

Fetch all users stored in the database:

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

Retrieve User by ID (GET with Route Parameters)

Fetch a specific user using their ID. First, ensure that the ID is numeric:

// GET: Retrieve a user by ID
app.get('/api/users/:id', (req, res) => {
  const userId = parseInt(req.params.id);

  // Validate if userId is numeric
  if (isNaN(userId)) {
    return res.status(400).json({ message: 'Invalid user ID' });
  }

  // Find the user by ID
  const user = users.find(u => u.id === userId);

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

  res.json(user);
});

Update User (PUT Request)

Update a specific user's details. Ensure the user exists before modifying their data:

// PUT: Update existing user
app.put('/api/users/:id', (req, res) => {
  const userId = parseInt(req.params.id);

  // Validate if userId is numeric
  if (isNaN(userId)) {
    return res.status(400).json({ message: 'Invalid user ID' });
  }

  const userIndex = users.findIndex(u => u.id === userId);

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

  // Update the user's details with the provided data
  users[userIndex] = {
    ...users[userIndex],
    name: req.body.name || users[userIndex].name,
    email: req.body.email || users[userIndex].email
  };

  res.json({ message: 'User updated successfully', user: users[userIndex] });
});

Delete User (DELETE Request)

Delete a user by their ID:

// DELETE: Remove a user
app.delete('/api/users/:id', (req, res) => {
  const userId = parseInt(req.params.id);

  // Validate if userId is numeric
  if (isNaN(userId)) {
    return res.status(400).json({ message: 'Invalid user ID' });
  }

  const userIndex = users.findIndex(u => u.id === userId);

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

  // Remove the user from the array
  users.splice(userIndex, 1);

  res.json({ message: 'User deleted successfully' });
});

Running the Server

Start the server with the following command:

node server.js

Your server will be accessible at:

http://localhost:3000

Testing the API

Use tools like Postman or curl to test your API endpoints:

  1. Retrieve all users (GET):
    curl http://localhost:3000/api/users
    
  2. Retrieve a specific user (GET):
    curl http://localhost:3000/api/users/1
    
  3. Create a new user (POST):
    curl -X POST -H "Content-Type: application/json" -d '{"name":"Neha Sharma", "email":"[email protected]"}' http://localhost:3000/api/users
    
  4. Update a user (PUT):
    curl -X PUT -H "Content-Type: application/json" -d '{"name":"Neha Updated"}' http://localhost:3000/api/users/3
    
  5. Delete a user (DELETE):
    curl -X DELETE http://localhost:3000/api/users/3
    

Conclusion

In this tutorial, you learned how to create a REST API using Express.js with basic CRUD operations for user management. This setup demonstrates how you can quickly build a robust backend service with Express.js. You can extend this project by adding features like database integration, authentication, and input validation.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram