Course Content
Introduction to Node.JS
0/1
Installation
0/1
Feature of Node.JS
0/1
Types of File Operations
0/1
Routing, Params, Request, and Response
0/1
HTTP Status Codes
0/1
Node JS
About Lesson

HTTP Methods in REST API (Including PATCH)

HTTP MethodPurposeExample URLExample Action
GETRetrieve data/usersGet a list of users
POSTCreate new data/usersAdd a new user
PUTUpdate entire data/users/1Replace user with ID 1
PATCHUpdate partial data/users/1Modify only specific fields of user with ID 1
DELETERemove data/users/1Delete user with ID 1

Example

JavaScript
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
let users = [
    { id: 1, name: "John Doe", email: "john@example.com" },
    { id: 2, name: "Jane Doe", email: "jane@example.com" }
];

app.get('/', (req, res) => res.send('Welcome to our REST API!'));
app.get('/users', (req, res) => res.json(users));
app.get('/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) return res.status(404).json({ message: "User not found" });
    res.json(user);
});

app.post('/users', (req, res) => {
    const newUser = {
        id: users.length + 1,
        name: req.body.name,
        email: req.body.email
    };
    users.push(newUser);
    res.status(201).json(newUser);
});

app.put('/users/:id', (req, res) => {
    let user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) return res.status(404).json({ message: "User not found" });

    user.name = req.body.name;
    user.email = req.body.email;
    res.json(user);
});

app.patch('/users/:id', (req, res) => {
    let user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) return res.status(404).json({ message: "User not found" });

    if (req.body.name) user.name = req.body.name;
    if (req.body.email) user.email = req.body.email;
    
    res.json(user);
});

app.delete('/users/:id', (req, res) => {
    users = users.filter(u => u.id !== parseInt(req.params.id));
    res.json({ message: "User deleted" });
});

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

REST API Best Practices

  • Use Proper HTTP Methods – Follow the correct method for each action
  • Use Meaningful Endpoints – Instead of /getUserData, use /users.
  • Use JSON Format – JSON is lightweight and widely used.
  • Implement Authentication – Use JWT (JSON Web Token) or API keys for security.
  • Use Status Codes Correctly – Always return the right status codes.