Lesson 36 of 50 – Building a REST API with Express.js
72% Completed
72%

Building a REST API with Express.js

Learn how to build a REST API using Node.js and Express.js, handle HTTP requests, return JSON data, and test API endpoints with Postman.

In this lesson: You will learn REST API concepts, HTTP methods, API endpoints, JSON responses, status codes, in-memory data, and how to test your API.

1. What Is an API?

API stands for Application Programming Interface. It allows different software applications to communicate with each other.

For example:

  • A website can request student information from a server.
  • A mobile app can retrieve product information from an API.
  • An application can submit registration data to a server.
How an API Works
Client Application

Website or mobile app

↓ HTTP Request
Express REST API

Processes the request

↓ JSON Response
Client Application

Uses the returned data

2. What Is a REST API?

REST stands for Representational State Transfer. A REST-style API exposes resources through URLs and commonly uses HTTP methods to retrieve or modify those resources.

Examples of resources include:

  • Students
  • Courses
  • Products
  • Orders
  • Employees
Example: A student management API might use /api/students to represent the collection of students and /api/students/101 to represent one student.

3. HTTP Methods Used in REST APIs

HTTP Method Purpose Example Endpoint
GET Retrieve data GET /api/students
POST Create a resource POST /api/students
PUT Replace a resource PUT /api/students/101
PATCH Partially update a resource PATCH /api/students/101
DELETE Delete a resource DELETE /api/students/101

4. Create a REST API Project

Follow these steps to create the project.

Step 1: Create a Folder
mkdir student-api
cd student-api
Step 2: Initialize the Project
npm init -y

This command creates a package.json file.

Step 3: Install Express.js
npm install express

5. Create Your First REST API

Create a file named app.js and add the following code.

app.js
const express = require('express');

const app = express();

app.get('/api', (req, res) => {
    res.json({
        message: 'Welcome to our REST API'
    });
});

app.listen(3000, () => {
    console.log('API running at http://localhost:3000');
});

Run the server:

node app.js

Open:

http://localhost:3000/api

Expected response:

{
  "message": "Welcome to our REST API"
}

6. Create a Student REST API

Now create an API that returns a list of students and allows a client to retrieve one student by ID.

Example: Get All Students and One Student
const express = require('express');

const app = express();

const students = [
    { id: 1, name: 'Amit', course: 'Node.js' },
    { id: 2, name: 'Rahul', course: 'JavaScript' },
    { id: 3, name: 'Priya', course: 'React' }
];

app.get('/api/students', (req, res) => {
    res.json(students);
});

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

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

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

    res.json(student);
});

app.listen(3000, () => {
    console.log('API running on port 3000');
});

Get all students:

GET http://localhost:3000/api/students

Get student with ID 2:

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

Example response:

{
  "id": 2,
  "name": "Rahul",
  "course": "JavaScript"
}
The student records are stored in an in-memory array. They will reset when the server restarts. A database will be introduced in later lessons.

7. Create a Student Using POST

The POST method is commonly used to create a new resource. To read JSON request bodies, register express.json().

Example: Add a Student
const express = require('express');
const app = express();

app.use(express.json());

const students = [
    { id: 1, name: 'Amit', course: 'Node.js' }
];

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({
            message: 'Name and course are required'
        });
    }

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

    students.push(newStudent);

    res.status(201).json(newStudent);
});

app.listen(3000, () => {
    console.log('API running on port 3000');
});

Send a POST request to http://localhost:3000/api/students with this JSON body:

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

Example response:

{
  "id": 2,
  "name": "Neha",
  "course": "Python"
}

The response uses status code 201 Created.

8. Update a Student Using PUT

PUT is commonly used to replace the data of an existing resource. This example expects both the name and course to be supplied.

Example: Update a Student
app.put('/api/students/:id', (req, res) => {
    const id = Number(req.params.id);
    const student = students.find(s => s.id === id);

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

    const { name, course } = req.body;

    if (
        typeof name !== 'string' ||
        !name.trim() ||
        typeof course !== 'string' ||
        !course.trim()
    ) {
        return res.status(400).json({
            message: 'Name and course are required'
        });
    }

    student.name = name.trim();
    student.course = course.trim();

    res.json({
        message: 'Student updated successfully',
        student: student
    });
});

Send a PUT request to http://localhost:3000/api/students/1 with a JSON body containing the updated name and course.

9. Update Part of a Student Using PATCH

PATCH updates selected fields without requiring the client to send every field.

Example: Partial Update
app.patch('/api/students/:id', (req, res) => {
    const id = Number(req.params.id);
    const student = students.find(s => s.id === id);

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

    const { name, course } = req.body;

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

        student.name = name.trim();
    }

    if (course !== undefined) {
        if (typeof course !== 'string' || !course.trim()) {
            return res.status(400).json({
                message: 'Course must be a non-empty string'
            });
        }

        student.course = course.trim();
    }

    res.json({
        message: 'Student updated successfully',
        student: student
    });
});

For example, a PATCH request can update only the student's course.

10. Delete a Student Using DELETE

The DELETE method is used to remove a resource.

Example: Delete a Student
app.delete('/api/students/:id', (req, res) => {
    const id = Number(req.params.id);
    const index = students.findIndex(s => s.id === id);

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

    students.splice(index, 1);

    res.json({
        message: 'Student deleted successfully'
    });
});

Send a DELETE request to http://localhost:3000/api/students/1.

11. Common HTTP Status Codes for APIs

Status Code Meaning Example Use
200 OK Data retrieved or an operation succeeded.
201 Created A resource was created.
204 No Content An operation succeeded without a response body.
400 Bad Request Required fields are missing or invalid.
404 Not Found The requested student does not exist.
500 Internal Server Error An unexpected server-side problem occurred.

12. Test Your REST API with Postman

Postman is an API client that allows you to send HTTP requests and inspect the responses.

Steps to Test the API
  1. Start your server using node app.js.
  2. Open Postman.
  3. Select an HTTP method such as GET or POST.
  4. Enter the API URL.
  5. For POST, PUT, or PATCH, select Body → raw → JSON.
  6. Enter your JSON data.
  7. Click Send and inspect the status code and response.
Important: The separate examples above demonstrate individual endpoints. To test all CRUD operations together, combine the route handlers into one app.js file, declare the shared students array once, and register app.use(express.json()) before the routes.

13. Practical Assignment

Assignment: Build a Student REST API

Create a complete Express API with the following requirements:

  1. Create a project named student-api.
  2. Install Express.js.
  3. Create a GET endpoint to return all students.
  4. Create a GET endpoint to retrieve one student by ID.
  5. Create a POST endpoint to add a student.
  6. Create a PUT endpoint to replace a student's details.
  7. Create a PATCH endpoint to update one or more fields.
  8. Create a DELETE endpoint to remove a student.
  9. Validate required fields before saving or updating data.
  10. Return appropriate HTTP status codes and JSON messages.
  11. Test every endpoint using Postman.
Lesson Summary: You learned what REST APIs are, how HTTP methods map to common operations, how to build Express endpoints, how to work with JSON requests and responses, and how to test a basic CRUD API. This example uses in-memory data rather than a database.

Test Your Knowledge – MCQ Quiz

Select the correct answer for each question.

1. Which HTTP method is commonly used to create a resource?
2. Which Express middleware parses JSON request bodies?
3. Which status code commonly indicates that a resource was created?