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

GET Requests in REST API

GET is an HTTP method used to retrieve information from a server through a REST API.

When a user opens a product page, views a list of courses, or checks their profile, the application commonly sends a GET request to retrieve the required data.

In Node.js and Express.js, we can create GET endpoints using app.get(). These endpoints can return JSON data, individual resources, or lists of resources to the client.

1. What Is a GET Request?

A GET request asks the server to retrieve a representation of a resource. It is commonly used when an application needs to read information without changing the resource on the server.

For example, an application may use these endpoints:

  • GET /api/products — retrieve all products.
  • GET /api/products/101 — retrieve a product with ID 101.
  • GET /api/courses — retrieve available courses.
Remember: GET requests should be safe to repeat and should not be designed to create, update, or delete resources. They may still produce logs or other incidental server-side effects.

2. How a GET Request Works

The client sends a GET request to an endpoint. Express matches the requested path, executes the route handler, and returns the requested data.

Step 1: Client

Requests product information

↓
Step 2: GET Endpoint

GET /api/products

↓
Step 3: Express Route Handler

Finds and prepares the requested data

↓
Step 4: JSON Response

Returns product information and a status code

↓
Step 5: Client

Displays the received information

For example, when the client requests /api/products, the server may return an array containing all available products.

3. Creating a Simple GET API

Let us create a GET endpoint that returns a list of products stored in a JavaScript array.

Step 1: Create app.js

JavaScript
const express = require('express');

const app = express();

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

// GET endpoint
app.get('/api/products', (req, res) => {
    res.status(200).json(products);
});

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

Step 2: Install Express.js

Terminal
npm init -y
npm install express

Step 3: Run the application

Terminal
node app.js

Expected terminal output:

Output
Server running on port 3000

Step 4: Open the endpoint

http://localhost:3000/api/products

Expected JSON response:

JSON
[
    {
        "id": 1,
        "name": "Laptop",
        "price": 55000
    },
    {
        "id": 2,
        "name": "Keyboard",
        "price": 1500
    },
    {
        "id": 3,
        "name": "Mouse",
        "price": 700
    }
]

The app.get() method registers the GET endpoint. The res.status(200) call sets the success status, and res.json() sends the array as a JSON response.

Note: This example uses in-memory data. The product array is not stored permanently in a database.

4. GET Request Using Route Parameters

Sometimes we need to retrieve one specific resource instead of the entire collection. Route parameters allow us to identify the resource through the URL.

For example, /api/products/2 requests the product with ID 2.

JavaScript
const express = require('express');

const app = express();

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

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

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

    if (!Number.isInteger(id) || id <= 0) {
        return res.status(400).json({
            message: 'Invalid product ID'
        });
    }

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

    res.status(200).json(product);
});

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

Test this URL:

http://localhost:3000/api/products/2

Expected response:

JSON
{
    "id": 2,
    "name": "Keyboard",
    "price": 1500
}

The value :id is a route parameter. Express makes its value available through req.params.id. The application converts it to a number and searches for the matching product.

Remember: Validate route parameters before using them. Return a 400 response for invalid input and a 404 response when a validly formatted ID does not identify an existing product.

5. GET Request Using Query Parameters

Query parameters are commonly used to filter, search, sort, or paginate a collection of resources.

For example, the URL /api/products?category=electronics contains a query parameter named category.

JavaScript
const express = require('express');

const app = express();

const products = [
    { id: 1, name: 'Laptop', category: 'electronics' },
    { id: 2, name: 'Keyboard', category: 'accessories' },
    { id: 3, name: 'Mouse', category: 'accessories' }
];

app.get('/api/products', (req, res) => {
    const category = req.query.category;

    let result = products;

    if (category) {
        result = products.filter(
            product => product.category === category
        );
    }

    res.status(200).json(result);
});

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

Request URL:

http://localhost:3000/api/products?category=accessories

Expected response:

JSON
[
    {
        "id": 2,
        "name": "Keyboard",
        "category": "accessories"
    },
    {
        "id": 3,
        "name": "Mouse",
        "category": "accessories"
    }
]

Express provides query parameters through req.query. The example filters the product array and returns only products that match the requested category.

6. Diagram 2: Route Parameters vs Query Parameters

Both route parameters and query parameters provide information through a URL, but they are commonly used for different purposes.

Example URL 1

/api/products/101

↓
Route Parameter

req.params.id gives the value 101.

Example URL 2

/api/products?category=electronics

↓
Query Parameter

req.query.category gives the value electronics.

Feature Route Parameter Query Parameter
Example /products/101 /products?category=electronics
Access in Express req.params req.query
Common purpose Identify a specific resource Filter or customize a collection request

7. Common HTTP Status Codes for GET Requests

Status Code Meaning Example
200 OK The request succeeded. Products were returned successfully.
400 Bad Request The request contains invalid input. A product ID is not valid.
401 Unauthorized Valid authentication credentials are missing or invalid. An endpoint requires authentication.
404 Not Found The requested resource was not found. No product exists with the requested ID.
500 Internal Server Error An unexpected server-side error occurred. A database operation fails unexpectedly.

8. Best Practices for GET APIs

  • Use clear resource-based endpoint names.
  • Use GET requests to retrieve data rather than modify resources.
  • Validate route and query parameters.
  • Return appropriate status codes.
  • Use pagination when retrieving large collections.
  • Do not expose private information without proper authorization.
  • Use a database when data must persist beyond the server process.

Important Points to Remember

  • GET requests are used to retrieve resources.
  • Use app.get() to define a GET endpoint in Express.js.
  • Use res.json() to return JSON data.
  • Access route parameters through req.params.
  • Access query parameters through req.query.
  • Use status code 200 for a successful retrieval.
  • Use 400 for invalid input and 404 when the requested resource does not exist.
  • GET requests should not be designed to modify server resources.

Summary

GET is an HTTP method used to retrieve information from a REST API. Express.js provides app.get() for defining endpoints that return resources as JSON or other supported response formats.

Route parameters help identify specific resources, while query parameters commonly support filtering and searching. Proper validation and status codes make GET endpoints easier to use and maintain.