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

REST API Introduction in Node.js

REST API is a common way for applications to communicate with each other using HTTP requests and responses.

For example, a website may need to display products stored on a server. Instead of storing all product information in the browser, the website can send an HTTP request to a REST API. The server processes the request and returns the product information, commonly in JSON format.

Node.js and Express.js allow us to build REST APIs that receive requests, process data, interact with databases, and return appropriate responses to clients.

1. What Is an API?

API stands for Application Programming Interface. It defines how one software application can communicate with another application or service.

Imagine that you are using an institute website to view available courses. The website requests course information from the server. The server returns the data, and the website displays it. The API provides the communication interface between them.

Client Application

Requests course information

↓
API

Defines how the request and response are exchanged

↓
Server

Processes the request and returns course data

The client does not need to know every internal detail of the server. It only needs to send a request in the format supported by the API and process the response.

2. What Is a REST API?

REST stands for Representational State Transfer. It is an architectural style used to design networked applications. A REST API commonly exposes resources through URLs and uses standard HTTP methods to perform operations on those resources.

For example, an API for managing products might provide endpoints to retrieve products, create a product, update product information, and delete a product.

HTTP Method Purpose Example Endpoint
GET Retrieve resource information. /api/products
POST Create a new resource. /api/products
PUT Replace a resource representation. /api/products/101
PATCH Partially update a resource. /api/products/101
DELETE Delete a resource. /api/products/101
Remember: These are common REST API conventions. The exact behavior depends on how the API endpoint is implemented.

3. Why Do We Need REST APIs?

REST APIs allow different applications to exchange data without requiring them to use the same programming language or user interface.

  • A website can retrieve information from a server.
  • A mobile application can use the same backend API.
  • A frontend application can communicate with a database-backed server.
  • Applications can expose reusable services to other authorized clients.
  • Frontend and backend development can be organized separately.

For example, a Node.js backend may return JSON data while the frontend is developed using React, Angular, or plain JavaScript. The frontend can display the returned data without needing to know how the backend stores it.

4. How a REST API Works

A REST API follows a request-response communication pattern. The client sends an HTTP request to an endpoint, and the server returns a response containing a status code and, when appropriate, response data.

Step 1: Client

Sends an HTTP request

↓
Step 2: Express.js Server

Receives the request and matches the endpoint

↓
Step 3: Application Logic

Processes data or interacts with a database

↓
Step 4: API Response

Returns a status code and response data

↓
Step 5: Client

Reads and displays the response

For example, when a client requests GET /api/products, the server can retrieve product records and return them as a JSON array.

5. What Is an Endpoint?

An endpoint is a URL path through which a client accesses a particular API operation or resource.

Consider the following product API endpoints:

Endpoint Method Operation
/api/products GET Retrieve all products
/api/products/101 GET Retrieve product with ID 101
/api/products POST Create a product
/api/products/101 DELETE Delete product with ID 101

Notice that the same path can support different operations depending on the HTTP method. For example, GET /api/products retrieves products, while POST /api/products can create a new product.

6. What Is JSON in a REST API?

JSON stands for JavaScript Object Notation. It is a text-based data format commonly used to exchange structured information between a client and a server.

Example product data returned by an API:

JSON
{
    "id": 101,
    "name": "Laptop",
    "price": 55000,
    "inStock": true
}

In this example, the product has an ID, a name, a price, and an availability value. The client can read these properties and display them in a user interface.

Remember: JSON is a common response format, but REST APIs can use other representations when required.

7. Creating Your First REST API in Express.js

Let us create a simple REST API that returns a list of products. This example uses in-memory data, so the products are not saved permanently in a database.

Step 1: Create a project folder

Terminal
mkdir rest-api-demo
cd rest-api-demo
npm init -y
npm install express

Step 2: 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('REST API running at http://localhost:3000');
});

Step 3: Start the server

Terminal
node app.js

Expected terminal output:

Output
REST API running at http://localhost:3000

Step 4: Test the endpoint

Open this URL in your browser:

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 browser sends a GET request to the endpoint. Express matches the route, executes its callback, and returns the products using res.status(200).json(products).

8. Understanding HTTP Status Codes

An HTTP status code indicates the result of a request. REST APIs should return suitable status codes so clients can understand whether an operation succeeded or failed.

Status Code Meaning Typical Use
200 OK A request completed successfully.
201 Created A new resource was created successfully.
400 Bad Request The request contains invalid input.
401 Unauthorized Valid authentication credentials are missing or invalid.
404 Not Found The requested resource or endpoint was not found.
500 Internal Server Error An unexpected server-side error occurred.

Important Points to Remember

  • API stands for Application Programming Interface.
  • REST stands for Representational State Transfer.
  • REST APIs commonly expose resources through URL endpoints.
  • HTTP methods describe the operation requested by the client.
  • JSON is a common format for exchanging API data.
  • Express.js can create API endpoints using route methods such as app.get().
  • Use suitable HTTP status codes for success and error responses.
  • The sample product array is temporary in-memory data, not database storage.

Summary

A REST API allows applications to communicate using HTTP requests and responses. It commonly uses resource-based endpoints, HTTP methods, JSON data, and status codes.

With Node.js and Express.js, we can create API endpoints that retrieve, create, update, and delete resources. Understanding these fundamentals prepares us to build individual GET, POST, PUT, PATCH, and DELETE endpoints.