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

Products JSON API in Node.js

A Products JSON API is an API that returns product information in JSON format. In Node.js, we can create an HTTP server that handles requests and sends product data to the client.

In this lesson, we will learn how to create a Products JSON API, retrieve all products, retrieve a single product by ID, handle HTTP routes, and return appropriate status codes.


1. What Is a Products JSON API?

A Products JSON API allows a client application to request product information from a server. The server returns the requested information in JSON format.

For example, Samadhan wants to display products on a website. The website sends a request to the Node.js server, and the server returns product details such as ID, name, price, and category.

JSON
[
    {
        "id": 1,
        "name": "Laptop",
        "price": 55000,
        "category": "Electronics"
    },
    {
        "id": 2,
        "name": "Keyboard",
        "price": 1500,
        "category": "Accessories"
    }
]

Here, the API returns two products as a JSON array. Each product is represented as a JavaScript object before being converted into JSON text for the HTTP response.

2. How Does a Products API Work?

The client sends an HTTP request to a specific API route. The Node.js server checks the request method and URL, retrieves the required product data, and sends a response.

Client / Browser

Requests product information

↓
Node.js HTTP Server

Checks the HTTP method and route

↓
Products Array

Finds the required product data

↓
JSON Response

Returns product information to the client

3. Creating a Products JSON API

First, import the built-in HTTP module. Then create an array containing product information and use http.createServer() to create the API server.

Example:

server.js
const http = require('http');

const products = [
    {
        id: 1,
        name: 'Laptop',
        price: 55000,
        category: 'Electronics'
    },
    {
        id: 2,
        name: 'Keyboard',
        price: 1500,
        category: 'Accessories'
    },
    {
        id: 3,
        name: 'Mouse',
        price: 800,
        category: 'Accessories'
    }
];

const server = http.createServer((req, res) => {

    res.setHeader(
        'Content-Type',
        'application/json; charset=utf-8'
    );

    if (req.method === 'GET' && req.url === '/api/products') {

        res.writeHead(200);

        res.end(JSON.stringify(products));

    } else {

        res.writeHead(404);

        res.end(JSON.stringify({
            message: 'API route not found'
        }));
    }
});

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

In this example, the server checks whether the client sends a GET request to /api/products. If the route matches, the server returns the complete product list.

If the requested route does not match, the server returns HTTP status 404 Not Found.

4. Understanding the Code

Code Explanation
require('http') Imports Node.js's built-in HTTP module.
const products = [...] Stores the sample product data in an array.
http.createServer() Creates an HTTP server to handle incoming requests.
req.method Checks the HTTP method used by the client.
req.url Checks the requested URL path.
res.setHeader() Sets the response Content-Type header.
JSON.stringify(products) Converts the JavaScript product array into JSON text.
res.writeHead(200) Sets the HTTP status to 200 OK.
res.end() Sends the response and finishes it.
server.listen(3000) Starts the server on port 3000.

5. Running the Products API

Save the code in a file named server.js. Open a terminal in the same folder and execute the following command.

Terminal
node server.js

Expected output:

Terminal Output
Products API running at http://localhost:3000

The server is now listening on port 3000 and can receive HTTP requests from a browser or another client.

6. Getting All Products

To retrieve all products, send a GET request to the following URL:

API URL
http://localhost:3000/api/products

You can open this URL in a browser while the server is running. The server returns the product array as JSON.

Expected response:

JSON Response
[
    {
        "id": 1,
        "name": "Laptop",
        "price": 55000,
        "category": "Electronics"
    },
    {
        "id": 2,
        "name": "Keyboard",
        "price": 1500,
        "category": "Accessories"
    },
    {
        "id": 3,
        "name": "Mouse",
        "price": 800,
        "category": "Accessories"
    }
]

The response status is 200 OK because the server successfully returned the product list.

7. Getting a Single Product by ID

Sometimes a client needs only one product instead of the complete product list. We can use the product ID to find the required product.

Add the following route before the final else block inside http.createServer().

JavaScript
else if (req.method === 'GET' && req.url === '/api/products/1') {

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

    if (product) {
        res.writeHead(200);

        res.end(JSON.stringify(product));
    } else {
        res.writeHead(404);

        res.end(JSON.stringify({
            message: 'Product not found'
        }));
    }
}

The find() method searches the array and returns the first product that matches the specified condition.

Request URL:

API URL
http://localhost:3000/api/products/1

Expected response:

JSON Response
{
    "id": 1,
    "name": "Laptop",
    "price": 55000,
    "category": "Electronics"
}

This route is specifically written for product ID 1. To support every product ID dynamically, the server would need to extract and validate the ID from the requested URL.

8. Handling Unknown Routes

If a client requests a URL that the server does not support, the API should return an appropriate error response.

Example:

JavaScript
else {
    res.writeHead(404);

    res.end(JSON.stringify({
        message: 'API route not found'
    }));
}

Request URL:

API URL
http://localhost:3000/unknown

Expected response:

JSON Response
{
    "message": "API route not found"
}

HTTP status 404 Not Found indicates that the requested route was not found on the server.

9. Testing the Products API Using curl

We can use the curl command to send requests to the API from a terminal.

Get all products:

Terminal
curl -i http://localhost:3000/api/products

Get the product with ID 1:

Terminal
curl -i http://localhost:3000/api/products/1

Request an unknown route:

Terminal
curl -i http://localhost:3000/unknown

The -i option displays the HTTP response headers along with the response body, so you can check the status code.

10. Important HTTP Status Codes

Status Code Meaning Usage
200 OK Request successful. Product data is returned.
404 Not Found Requested resource was not found. Unknown API route or missing product.

11. Practice Tasks

Task 1: Create a Products API

  1. Create a file named server.js.
  2. Import the built-in http module.
  3. Create an array containing at least three products.
  4. Create a GET route named /api/products.
  5. Return all products in JSON format.

Expected result: The API should return all products when the client requests /api/products.

Task 2: Retrieve a Single Product

  1. Add a route for retrieving one product.
  2. Use the product ID to find the required product.
  3. Return the product as JSON.
  4. Return HTTP status 404 when the product is not found.

Expected result: The API should return the selected product or an appropriate not-found response.

Summary

In this lesson, we created a simple Products JSON API using Node.js's built-in HTTP module. We learned how to create product data, handle GET requests, return all products, retrieve a predefined product, and handle unknown routes.

We also used JSON.stringify() to convert JavaScript data into JSON text and learned how HTTP status codes communicate the result of a request.

Remember the flow: Client Request → Check Route → Find Product Data → Convert to JSON → Send HTTP Response.