Paramclasses Academy - Blog

Tutorials Details

←
Post 20 of 40
→

How to Build REST APIs with Node.js and Express.js

How to Build REST APIs with Node.js and Express.js

October 29, 2026

✦ How to Build REST APIs with Node.js and Express.js

❖ Introduction to REST APIs

REST APIs are an essential part of modern web development. They allow different applications to communicate with each other and exchange data over HTTP. For example, a website can use an API to retrieve student details, a mobile application can use an API to display products, and an admin panel can use an API to update customer records.

Node.js allows developers to execute JavaScript on the server, while Express.js makes it easier to create API routes and handle HTTP requests.

In this tutorial, we will build a simple Student Management REST API using Node.js and Express.js. You will learn how to create API endpoints, send JSON responses, perform CRUD operations, validate incoming data, and test your API using Postman.

✦ What Is a REST API?

REST stands for Representational State Transfer. A REST API uses HTTP requests to access and manipulate resources.

For example, a Student Management API may provide these endpoints:

HTTP Method Endpoint Purpose
GET /api/students Get all students
GET /api/students/1 Get one student
POST /api/students Create a student
PUT /api/students/1 Replace student details
PATCH /api/students/1 Update selected fields
DELETE /api/students/1 Delete a student

 

   

A REST API typically returns data in JSON format, uses meaningful URLs, and communicates success or failure through HTTP status codes.

✦ Step 1: Set Up Your Node.js Project

First, install Node.js from the official website:

https://nodejs.org/

Open your terminal or command prompt and run:

mkdir student-rest-api
cd student-rest-api
npm init -y
npm install express

Create a file named app.js.

Your project structure will look like this:

student-rest-api/
├── node_modules/
├── app.js
├── package.json
└── package-lock.json

We will use Express.js to create the server and define API endpoints.

✦ Step 2: Create the Express.js Server

Add the following code to app.js:

const express = require("express");

const app = express();
const PORT = 3000;

// Parse incoming JSON request bodies
app.use(express.json());

// Test API route
app.get("/", (req, res) => {
    res.json({
        message: "Student Management REST API is running"
    });
});

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

Start the server:

node app.js

Open http://localhost:3000 in your browser. You should receive a JSON response confirming that the API is running.

The express.json() middleware allows Express to parse JSON request bodies so that routes can access submitted data through req.body.

✦ Step 3: Create a GET API to Retrieve Students

Now let's create an endpoint that returns all students.

Add this code before app.listen():

let students = [
    { id: 1, name: "Rahul", course: "Node.js" },
    { id: 2, name: "Priya", course: "PHP" },
    { id: 3, name: "Amit", course: "Python" }
];

app.get("/api/students", (req, res) => {
    res.status(200).json({
        success: true,
        data: students
    });
});

Visit:

http://localhost:3000/api/students

The API returns a JSON object containing the student records.

Here, res.status(200) indicates a successful request, while res.json() sends a JSON response to the client.

✦ Step 4: Get a Single Student Using Route Parameters

Sometimes, an application needs only one student's details. We can use the student ID as a route parameter.

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

    const student = students.find(item => item.id === id);

    if (!student) {
        return res.status(404).json({
            success: false,
            message: "Student not found"
        });
    }

    res.status(200).json({
        success: true,
        data: student
    });
});

Example URL:

http://localhost:3000/api/students/2

Express reads the ID using req.params.id. The API searches for a matching student and returns the record if it exists.

If the requested student does not exist, the API returns 404 Not Found.

✦ Step 5: Create a Student Using POST

The POST method is used to create a new resource.

Add the following route:

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"
        });
    }

    const newStudent = {
        id: students.length
            ? Math.max(...students.map(item => item.id)) + 1
            : 1,
        name: name.trim(),
        course: course.trim()
    };

    students.push(newStudent);

    res.status(201).json({
        success: true,
        message: "Student created successfully",
        data: newStudent
    });
});

To test this endpoint in Postman:

  1. Select the POST method.

  2. Enter http://localhost:3000/api/students.

  3. Open Body → raw → JSON.

  4. Enter the following data:

{
    "name": "Neha",
    "course": "JavaScript"
}

Send the request. The API should return 201 Created with the newly created student.

This example validates the required fields. A production API should also enforce appropriate field lengths, stronger validation, and database constraints.

✦ Step 6: Update Student Details Using PUT

The PUT method is generally used to replace the editable representation of a resource.

app.put("/api/students/:id", (req, res) => {
    const id = Number(req.params.id);
    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"
        });
    }

    const index = students.findIndex(item => item.id === id);

    if (index === -1) {
        return res.status(404).json({
            success: false,
            message: "Student not found"
        });
    }

    students[index] = {
        id,
        name: name.trim(),
        course: course.trim()
    };

    res.status(200).json({
        success: true,
        message: "Student updated successfully",
        data: students[index]
    });
});

For example, send a PUT request to /api/students/1 with:

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

The route replaces the student's editable fields with the submitted values.

✦ Step 7: Update Selected Fields Using PATCH

PATCH is useful when you want to update only selected fields without replacing the entire resource.

app.patch("/api/students/:id", (req, res) => {
    const id = Number(req.params.id);
    const student = students.find(item => item.id === id);

    if (!student) {
        return res.status(404).json({
            success: false,
            message: "Student not found"
        });
    }

    const { name, course } = req.body;

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

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

    if (Object.hasOwn(req.body, "name")) {
        student.name = name.trim();
    }

    if (Object.hasOwn(req.body, "course")) {
        student.course = course.trim();
    }

    res.status(200).json({
        success: true,
        message: "Student details updated",
        data: student
    });
});

For example, send a PATCH request to /api/students/2 with:

{
    "course": "Express.js"
}

Only the course changes; the student's name remains the same.

✦ Step 8: Delete a Student Using DELETE

The DELETE method removes a resource.

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

    if (index === -1) {
        return res.status(404).json({
            success: false,
            message: "Student not found"
        });
    }

    students.splice(index, 1);

    res.status(200).json({
        success: true,
        message: "Student deleted successfully"
    });
});

Send a DELETE request to:

http://localhost:3000/api/students/3

The API removes the matching student and returns a success message.

Important: The examples use an in-memory array instead of a database. Data changes are lost when the Node.js process restarts. For a real application, use a database such as MySQL or MongoDB.

✦ Step 9: Understand Common HTTP Status Codes

Status codes help API clients understand the outcome of a request.

Status Code Meaning
200 OK — request succeeded
201 Created — resource created
204 No Content — successful response without a body
400 Bad Request — invalid input
401 Unauthorized — authentication is missing or invalid
403 Forbidden — access is not allowed
404 Not Found — resource or route does not exist
500 Internal Server Error — unexpected server failure

 

 

Choose status codes that accurately describe the result. For example, use 400 for invalid submitted data and 404 when the requested student does not exist.

✦ Step 10: Test Your REST API

You can test your API using Postman or another HTTP client.

Test Method URL
Get all students GET /api/students
Get one student GET /api/students/1
Create student POST /api/students
Replace student PUT /api/students/1
Update a field PATCH /api/students/1
Delete student DELETE /api/students/1

For POST, PUT, and PATCH requests, select JSON in the request body settings and send valid JSON.

Test both successful and unsuccessful cases. For example, request a nonexistent student ID and confirm that the API returns a 404 response.

✦ Best Practices for Building REST APIs

  • Use consistent, resource-oriented endpoint names.

  • Validate and sanitize incoming data.

  • Use appropriate HTTP methods and status codes.

  • Keep routes, business logic, and database operations organized as your application grows.

  • Add authentication and authorization when the API handles private data.

  • Use environment variables for configuration and keep secrets out of source control.

  • Add structured error handling and useful server-side logging.

  • Use a persistent database instead of an in-memory array for real applications.

  • Document API endpoints so other developers can use them correctly.

✦ Frequently Asked Questions (FAQs)

1. What is a REST API in Node.js?

A REST API built with Node.js allows clients to communicate with a server through HTTP requests and exchange data, commonly in JSON format.

2. Why is Express.js used for REST APIs?

Express.js simplifies server creation, route management, middleware integration, and request-response handling.

3. What is the difference between PUT and PATCH?

PUT generally replaces the editable representation of a resource, while PATCH updates selected parts of it.

4. Can I build a REST API without a database?

Yes. You can practise API routes using arrays or other temporary storage, but the data will not persist after the application restarts.

5. How can I test a Node.js REST API?

Use Postman or another HTTP client to send requests, inspect JSON responses, and verify status codes.

✦ Conclusion

Building a REST API with Node.js and Express.js is an important step toward becoming a backend developer. By creating GET, POST, PUT, PATCH, and DELETE endpoints, you learn how applications retrieve, create, update, and remove resources.

Practise the Student Management API first, then connect it to MySQL or MongoDB to store data permanently. You can later add authentication, request validation, and role-based permissions to develop a more complete application.

Learn practical programming and backend development with Param Classes.

←
Post 20 of 40
→