Enhancing Your REST API: Implementing PUT, DELETE, and GET by Name in Node.js and Express

Enhancing Your REST API: Implementing PUT, DELETE, and GET by Name in Node.js and Express

        Building on our initial setup of a simple REST API for managing users, this blog will guide you through adding additional CRUD (Create, Read, Update, Delete) functionalities. We will incorporate methods to update existing users, delete users, and retrieve a user by name using Node.js and Express.

Extending the User API

Having previously set up basic GET and POST routes for our user management system, we’ll now add more complex interactions by allowing updates, deletions, and searching by name.

Setup

Ensure you have the following initial setup from the previous session:

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

const app = express();
app.use(cors());
app.use(express.json());

let users = [
    { id: 1, name: 'John Doe', email: 'john@example.com', phone: '1234567890', password: '$A123456'},
    { id: 2, name: 'Jane Doe', email: 'jane@example.com', phone: '0987654321', password: '$B123456'},
    { id: 3, name: 'Jim Doe', email: 'jim@example.com', phone: '1234567890', password: '$C123456'}
];

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

				
			

Implementing GET by Name

To retrieve a user by name, we add the following GET route:

				
					app.get('/api/users/:name', (req, res) => {
    const name = req.params.name;
    const user = users.find(user => user.name === name);
    if (user) {
        res.json(user);
    } else {
        res.status(404).json({ message: `User ${name} not found` });
    }
});

				
			

Implementing PUT to Update User Details

Updating user details is crucial for maintaining current data. We implement a PUT route as follows:

				
					app.put('/api/users/:name', (req, res) => {
    const name = req.params.name;
    const user = users.find(user => user.name === name);
    if (user) {
        const { email, phone, password } = req.body;
        user.email = email;
        user.phone = phone;
        user.password = password;
        res.json(user);
    } else {
        res.status(404).json({ message: `User ${name} not found` });
    }
});

				
			

Implementing DELETE to Remove a User

To allow users to be deleted from our array, we use the DELETE method:

				
					app.delete('/api/users/:name', (req, res) => {
    const name = req.params.name;
    const index = users.findIndex(user => user.name === name);
    if (index !== -1) {
        users.splice(index, 1);
        res.json({ message: `User ${name} deleted` });
    } else {
        res.status(404).json({ message: `User ${name} not found` });
    }
});

				
			

Testing the API

You can test these new functionalities using Postman or any other API testing tool by making requests to the respective endpoints with the appropriate HTTP methods and payloads.

        By extending our REST API with PUT, DELETE, and an additional GET method, we’ve significantly increased the capability of our application to interact with user data dynamically. These functionalities are critical for any full-featured REST API, providing the necessary tools for effective data management.

Overview

Leave a Reply

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

Enquire Now