Paramclasses Academy - Blog

Tutorials Details

←
Post 21 of 40
→

HTTP Methods and Status Codes for Node.js API Developers

HTTP Methods and Status Codes for Node.js API Developers

October 30, 2026

✦ HTTP Methods and Status Codes for Node.js API Developers

❖ Introduction

HTTP methods and status codes are essential concepts for every Node.js backend developer. When a website, mobile application, or frontend sends a request to a server, the HTTP method describes the requested operation, while the status code communicates the result.

For example, a student management application may use a GET request to retrieve student details, a POST request to register a new student, and a DELETE request to remove a record.

Node.js and Express.js make it straightforward to handle these requests and return appropriate status codes.

In this tutorial, we will explore the most commonly used HTTP methods, understand important status codes, and build a practical Express.js API that demonstrates how they work.

✦ What Are HTTP Methods?

HTTP methods indicate what a client wants the server to do with a resource.

For example, a REST API might use /api/students as the endpoint for student records. Different HTTP methods can perform different operations on that resource.

HTTP Method Common Purpose
GET Retrieve information
POST Create a resource or submit data
PUT Replace a resource representation
PATCH Partially update a resource
DELETE Delete a resource
HEAD Retrieve response headers without a response body
OPTIONS Discover supported communication options

 

 

GET, POST, PUT, PATCH, and DELETE are especially important when building REST APIs.

✦ 1. GET Method: Retrieve Data

The GET method is used to retrieve information from a server. For example, an application may request all students or fetch the details of a particular student.

Example:

app.get("/api/students", (req, res) => {
    res.status(200).json({
        success: true,
        message: "Students retrieved successfully",
        data: [
            { id: 1, name: "Rahul", course: "Node.js" },
            { id: 2, name: "Priya", course: "PHP" }
        ]
    });
});

When a client sends a GET request to /api/students, the API returns student information as JSON.

A GET request should not be used to intentionally create, update, or delete application data. GET is defined as a safe HTTP method.

✦ 2. POST Method: Create Data

The POST method is commonly used to submit data or create a new resource.

For example, a student registration form can send a POST request containing a student's name and course.

app.use(express.json());

app.post("/api/students", (req, res) => {
    const { name, course } = req.body;

    if (
        typeof name !== "string" ||
        !name.trim() ||
        typeof course !== "string" ||
        !course.trim()
    ) {
        return res.status(400).json({
            success: false,
            message: "Valid name and course are required"
        });
    }

    res.status(201).json({
        success: true,
        message: "Student data received",
        data: {
            name: name.trim(),
            course: course.trim()
        }
    });
});

Here, express.json() parses incoming JSON request bodies. The route checks the required fields and returns 201 Created when the submitted data passes validation.

This example does not store a student in a database. A complete registration API would save the record using a database such as MySQL or MongoDB.

✦ 3. PUT Method: Replace a Resource

PUT is generally used to replace the current representation of a resource with the supplied data.

app.put("/api/students/:id", (req, res) => {
    const studentId = Number(req.params.id);
    const { name, course } = req.body;

    if (
        !Number.isInteger(studentId) ||
        studentId <= 0 ||
        typeof name !== "string" ||
        !name.trim() ||
        typeof course !== "string" ||
        !course.trim()
    ) {
        return res.status(400).json({
            success: false,
            message: "Invalid student ID or student data"
        });
    }

    res.status(200).json({
        success: true,
        message: "Student replacement data validated",
        data: {
            id: studentId,
            name: name.trim(),
            course: course.trim()
        }
    });
});

A request to /api/students/1 might include the following JSON body:

{
    "name": "Rahul Sharma",
    "course": "Advanced Node.js"
}

The example validates the replacement data and returns it. It does not update a database, and a production implementation must also check whether the student exists before performing the update.

✦ 4. PATCH Method: Update Selected Fields

PATCH is useful when the client wants to change only part of a resource.

For example, a student may change their course without resubmitting their name.

app.patch("/api/students/:id", (req, res) => {
    const studentId = Number(req.params.id);
    const { course } = req.body;

    if (
        !Number.isInteger(studentId) ||
        studentId <= 0 ||
        typeof course !== "string" ||
        !course.trim()
    ) {
        return res.status(400).json({
            success: false,
            message: "Valid student ID and course are required"
        });
    }

    res.status(200).json({
        success: true,
        message: "Partial update data validated",
        data: {
            id: studentId,
            course: course.trim()
        }
    });
});

For example, the request body may contain only:

{
    "course": "Express.js"
}

This demonstration validates the partial-update data but does not persist changes. In a real API, the server would update the specified field in the database while preserving the other fields.

✦ 5. DELETE Method: Remove Data

The DELETE method requests the removal of a resource.

app.delete("/api/students/:id", (req, res) => {
    const studentId = Number(req.params.id);

    if (!Number.isInteger(studentId) || studentId <= 0) {
        return res.status(400).json({
            success: false,
            message: "Invalid student ID"
        });
    }

    // Perform the database deletion here.
    res.status(200).json({
        success: true,
        message: `Deletion requested for student ${studentId}`
    });
});

This example validates the ID and demonstrates the response format. It does not actually delete a database record.

A production implementation should check whether the record exists and perform the deletion before reporting success. A successful DELETE request may return 204 No Content when no response body is needed.

✦ What Are HTTP Status Codes?

HTTP status codes are three-digit numbers returned by a server to describe the result of a request.

They are divided into five groups:

  • 1xx – Informational: The request is still being processed or additional protocol information is provided.

  • 2xx – Success: The request was successfully received, understood, and handled.

  • 3xx – Redirection: Additional action is needed to complete the request.

  • 4xx – Client Error: The request has a problem, such as invalid input or missing authorization.

  • 5xx – Server Error: The server failed to fulfil an otherwise valid request.

Choosing the correct status code makes an API easier to understand, test, and maintain.

✦ Important HTTP Status Codes for Node.js Developers

Status Code Meaning Common Use
200 OK Request succeeded Successful GET or update
201 Created Resource created Successful POST that creates a resource
202 Accepted Request accepted for processing Asynchronous job submitted
204 No Content Success with no response body Successful DELETE
301 Moved Permanently Permanent redirection Resource moved to a new URL
302 Found Temporary redirection Temporary redirect
304 Not Modified Cached representation can be reused Conditional GET
400 Bad Request Invalid request Missing or malformed input
401 Unauthorized Authentication is required or invalid Missing or invalid credentials
403 Forbidden Access is not permitted Authenticated user lacks permission
404 Not Found Resource or route not found Student ID does not exist
405 Method Not Allowed Method is not supported for the resource Unsupported HTTP method
409 Conflict Request conflicts with current state Duplicate registration
422 Unprocessable Content Request content cannot be processed Validation failure under an API's chosen convention
429 Too Many Requests Too many requests received Rate limit exceeded
500 Internal Server Error Unexpected server failure Unhandled server-side error
502 Bad Gateway Invalid response from an upstream server Proxy or gateway failure
503 Service Unavailable Service temporarily unavailable Maintenance or overload
504 Gateway Timeout Upstream server did not respond in time Gateway timeout

Choose status codes based on the actual result of the operation. For example, do not return 201 Created if no resource was created.

✦ How to Send Status Codes in Express.js

Express provides the res.status() method to set an HTTP status code.

Example:

app.get("/api/profile", (req, res) => {
    res.status(200).json({
        success: true,
        message: "Profile retrieved successfully"
    });
});

You can also return an error:

app.get("/api/private", (req, res) => {
    return res.status(401).json({
        success: false,
        message: "Authentication required"
    });
});

The first route returns 200 OK, while the second returns 401 Unauthorized.

The .json() method sends a JSON response. Always use a status code that accurately describes what happened.

✦ Difference Between 401 and 403

These two status codes are often confused.

401 Unauthorized means the request lacks valid authentication credentials. For example, the user may not have supplied a valid access token.

403 Forbidden means the server understood the request but refuses to authorize it. For example, a logged-in student may try to access an administrator-only endpoint.

Remember this simple distinction:

  • 401: Valid authentication is missing or has failed.

  • 403: The requested action is not permitted.

✦ How to Test HTTP Methods in Postman

Postman allows you to test API endpoints without building a frontend.

Follow these steps:

  1. Start your Node.js server using node app.js.

  2. Open Postman and create a new HTTP request.

  3. Select GET, POST, PUT, PATCH, or DELETE.

  4. Enter the appropriate endpoint, such as http://localhost:3000/api/students.

  5. For methods that require data, select Body → raw → JSON and enter valid JSON.

  6. Click Send.

  7. Inspect the status code, response body, and any validation errors.

Test invalid IDs, missing fields, and unsupported operations as well as successful requests. Testing error cases is important for building reliable APIs.

✦ Best Practices for HTTP Methods and Status Codes

  • Use HTTP methods consistently with their intended semantics.

  • Keep GET requests safe and avoid using them to change application state.

  • Validate incoming request data before processing it.

  • Return accurate status codes for success, validation failures, and missing resources.

  • Use consistent JSON response structures across endpoints.

  • Avoid returning confidential information or internal stack traces to clients.

  • Check resource existence before reporting successful updates or deletions.

  • Use authentication and authorization where needed.

  • Document endpoints, request formats, and expected status codes.

  • Test your APIs with both valid and invalid inputs.

✦ Frequently Asked Questions (FAQs)

1. What is the difference between HTTP methods and status codes?

HTTP methods describe the operation a client requests, while status codes describe the outcome of that request.

2. Which HTTP method is used to retrieve data?

GET is commonly used to retrieve information from a server.

3. When should I use POST instead of PUT?

POST is commonly used to create resources or submit data for processing. PUT is generally used to replace a resource representation at a known target URL.

4. What is the difference between 200 and 201?

200 OK indicates success. 201 Created indicates that the request successfully created a resource.

5. When should an API return 404?

Return 404 Not Found when the requested resource or endpoint cannot be found.

6. What does status code 500 mean?

500 Internal Server Error indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.

✦ Conclusion

HTTP methods and status codes are foundational concepts for Node.js backend development. GET, POST, PUT, PATCH, and DELETE help define how an API interacts with resources, while status codes communicate the result to clients.

By practising these concepts with Express.js and Postman, you can create clearer, more consistent REST APIs. The next step is to connect your API to a database, add validation, implement authentication, and build a complete CRUD application.

Learn practical backend development with Param Classes.

←
Post 21 of 40
→