Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

PUT and PATCH Requests in Node.js

Learn how to update existing resources in a REST API using PUT and PATCH requests in Node.js.

In a REST API, we use HTTP methods to perform different operations on resources. The PUT and PATCH methods are mainly used to update existing data on the server.

For example, suppose we have a product with an ID of 1. If we want to update its name and price, we can use PUT. If we want to update only its price, we can use PATCH.

Remember: PUT is generally used to replace a resource, whereas PATCH is used to update selected fields of a resource.

1. What Is a PUT Request?

A PUT request is used to update or replace an existing resource. The client usually sends the complete representation of the resource that it wants to save.

For example, the existing product is:

JSON
{
    "id": 1,
    "name": "Laptop",
    "price": 50000
}

Now, suppose we want to change the product name and price. We send a PUT request with the updated product data.

JSON
{
    "name": "Gaming Laptop",
    "price": 75000
}

In a typical PUT implementation, the server replaces the existing resource representation with the supplied data. The exact handling of fields such as the ID depends on the API design.

Important: If a PUT endpoint expects the complete resource, sending only some fields may cause omitted fields to be reset or removed. Follow the contract defined by the API.

2. What Is a PATCH Request?

A PATCH request is used to update only selected fields of an existing resource. The client does not need to send every field.

Suppose the existing product is:

JSON
{
    "id": 1,
    "name": "Laptop",
    "price": 50000
}

If we want to change only the price, we can send the following data in a PATCH request.

JSON
{
    "price": 60000
}

The updated product will be:

JSON
{
    "id": 1,
    "name": "Laptop",
    "price": 60000
}
The product name remains unchanged because the PATCH request updates only the price.

3. Difference Between PUT and PATCH

Feature PUT PATCH
Purpose Replace or fully update a resource Update selected fields
Request body Usually contains the complete resource representation Contains the fields or changes to apply
Unsent fields May be reset or removed, depending on the API contract Usually remain unchanged
Example Update product name and price together Update only the product price
Common success status 200 OK or 204 No Content 200 OK or 204 No Content

4. Creating PUT and PATCH Routes

We can create PUT and PATCH routes in an Express application. The following example uses an in-memory array to demonstrate how existing product data can be updated.

JavaScript
const express = require('express');

const app = express();

app.use(express.json());

let products = [
    { id: 1, name: 'Laptop', price: 50000 },
    { id: 2, name: 'Mobile', price: 20000 }
];

// PUT: Replace the product details
app.put('/api/products/:id', (req, res) => {
    const id = Number(req.params.id);

    const index = products.findIndex(
        product => product.id === id
    );

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

    const { name, price } = req.body;

    if (
        typeof name !== 'string' ||
        name.trim() === '' ||
        typeof price !== 'number' ||
        !Number.isFinite(price) ||
        price < 0
    ) {
        return res.status(400).json({
            message: 'Valid name and price are required'
        });
    }

    products[index] = {
        id,
        name: name.trim(),
        price
    };

    res.status(200).json({
        message: 'Product replaced successfully',
        product: products[index]
    });
});

// PATCH: Update selected product fields
app.patch('/api/products/:id', (req, res) => {
    const id = Number(req.params.id);

    const product = products.find(
        product => product.id === id
    );

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

    const { name, price } = req.body;

    if (Object.keys(req.body).length === 0) {
        return res.status(400).json({
            message: 'At least one field is required'
        });
    }

    if (
        Object.hasOwn(req.body, 'name') &&
        (typeof name !== 'string' || name.trim() === '')
    ) {
        return res.status(400).json({
            message: 'Name must be a non-empty string'
        });
    }

    if (
        Object.hasOwn(req.body, 'price') &&
        (
            typeof price !== 'number' ||
            !Number.isFinite(price) ||
            price < 0
        )
    ) {
        return res.status(400).json({
            message: 'Price must be a non-negative number'
        });
    }

    if (Object.hasOwn(req.body, 'name')) {
        product.name = name.trim();
    }

    if (Object.hasOwn(req.body, 'price')) {
        product.price = price;
    }

    res.status(200).json({
        message: 'Product updated successfully',
        product
    });
});

app.listen(3000, () => {
    console.log('Server running at http://localhost:3000');
});
Note: This example stores data in memory. Changes will be lost when the Node.js server restarts. A production application should use a database and appropriate validation and authorization.

5. Understanding the PUT Route

The PUT route uses the product ID from the URL to locate the existing product. It then validates the request body and replaces the product with the supplied name and price.

JavaScript
app.put('/api/products/:id', (req, res) => {
    // Find the product
    // Validate the complete replacement data
    // Replace the existing product
});

Example request:

HTTP
PUT http://localhost:3000/api/products/1
Content-Type: application/json

Request body:

JSON
{
    "name": "Gaming Laptop",
    "price": 75000
}

Example response with status code 200 OK:

JSON
{
    "message": "Product replaced successfully",
    "product": {
        "id": 1,
        "name": "Gaming Laptop",
        "price": 75000
    }
}

6. Understanding the PATCH Route

The PATCH route finds the product and updates only the fields supplied in the request body. Fields that are not supplied remain unchanged.

Example request:

HTTP
PATCH http://localhost:3000/api/products/1
Content-Type: application/json

Request body:

JSON
{
    "price": 80000
}

Example response with status code 200 OK:

JSON
{
    "message": "Product updated successfully",
    "product": {
        "id": 1,
        "name": "Gaming Laptop",
        "price": 80000
    }
}
Notice that only the price changes. The product name stays "Gaming Laptop" because it was not included in the PATCH request.

7. PUT and PATCH Request Flow

Both methods follow a similar process, but the update operation differs.

Client

Sends PUT or PATCH request

↓
Express Route

Reads the ID and request body

↓
Find and Validate

Checks whether the product exists and data is valid

↓
PUT

Replaces the product representation

PATCH

Updates selected fields

↓
Response

Returns updated data or an error message

8. Common HTTP Status Codes

Status Code Meaning When to Use
200 OK Request completed successfully When returning the updated resource or a success message
204 No Content Request completed without a response body When the update succeeds and no content needs to be returned
400 Bad Request Request data is invalid When required fields or validation rules fail
404 Not Found Resource does not exist When the supplied product ID cannot be found

Important Points to Remember

  • PUT is generally used to replace a resource representation.
  • PATCH is generally used to update selected fields.
  • Use req.params.id to read the product ID from the URL.
  • Use req.body to access the parsed request body.
  • Use express.json() to parse incoming JSON request bodies.
  • Validate request data before changing existing records.
  • Return 404 when the requested product does not exist.
  • Use a database for persistent application data.

Summary

PUT and PATCH are HTTP methods used to update resources in a REST API. PUT generally replaces the resource representation, while PATCH modifies selected fields. Express routes can handle both methods by reading the URL parameters, validating the request body, updating the resource, and returning an appropriate HTTP response.

In the next lesson, we will learn how to delete resources using the DELETE request.