1. Home
  2. Explore
  3. Computer Science
  4. Node.js REST API

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Node.js REST API

πŸ’‘ Vanilla Node.js REST API with CRUD

This guide details how to build a Vanilla Node.js REST API with full CRUD (Create, Read, Update, Delete) functionality. Unlike typical tutorials that use frameworks like Express, this API is built using only bare-bones Node.js with the built-in http module. This approach, while requiring more manual coding, offers a deeper understanding of the underlying HTTP request-response cycle and how frameworks abstract these processes.


πŸš€ Project Setup & Dependencies

To begin, set up the project environment and install necessary dependencies.

πŸ“¦ Initializing Project

  1. Create a project folder, e.g., vanilla-node-rest-api.

  2. Inside the folder, initialize package.json:

      npm init -y

    This command creates a package.json file with default values, skipping the interactive questions.

πŸ“ Data Structure

The API will interact with a JSON file as its data source instead of a database.

  1. Create a data folder in the project root.

  2. Inside data, create products.json with an array of product objects.

    • Each product object should have id, name, description, and price.

      [
        {
          "id": "1",
          "name": "Airpods Wireless Bluetooth Headphones",
          "description": "Bluetooth technology lets you connect it to compatible devices from up to 30ft away",
          "price": 89.99
        },
        {
          "id": "2",
          "name": "iPhone 13 Pro",
          "description": "The latest iPhone model with advanced camera features and A15 Bionic chip.",
          "price": 999.99
        },
        {
          "id": "3",
          "name": "Sony PlayStation 5",
          "description": "Next-gen gaming console with ultra-high-speed SSD and immersive haptic feedback.",
          "price": 499.99
        },
        {
          "id": "4",
          "name": "MacBook Air M1",
          "description": "Lightweight and powerful laptop with Apple's M1 chip, offering incredible performance and battery life.",
          "price": 1199.99
        },
        {
          "id": "5",
          "name": "Samsung 4K Smart TV",
          "description": "Experience stunning 4K UHD resolution and smart features for endless entertainment.",
          "price": 799.99
        }
      ]

βš™οΈ Installing Dependencies

Only two third-party packages are used:

  • Nodemon: For automatically restarting the server on file changes during development.

  • UUID: For generating unique IDs for new products.

Install them:

npm install -D nodemon
npm install uuid
  • nodemon is installed as a dev dependency (-D).

πŸ“œ NPM Scripts

Add the following scripts to package.json for easy execution:

"scripts": {
  "start": "node server.js",
  "dev": "nodemon server.js"
}
  • npm start: For running the server in a production environment.

  • npm run dev: For running the server with nodemon for development.


🌐 Server Entry Point (server.js)

The server.js file is the entry point of the application, responsible for creating the HTTP server and handling incoming requests.

πŸ“¦ Importing HTTP Module

The http module is a built-in Node.js module that provides functionalities for creating HTTP servers and clients.

const http = require('http');

βš™οΈ Creating the Server

The http.createServer() method is used to create an HTTP server. It takes a callback function that executes every time a request is made to the server. This function receives req (request) and res (response) objects.

const server = http.createServer((req, res) => {
    // Request handling logic goes here
});

πŸ‘‚ Listening for Requests

The server needs to listen on a specific port for incoming connections.

const PORT = process.env.PORT || 5000;

server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
  • process.env.PORT allows specifying the port via an environment variable, useful for deployment.

  • If no environment variable is set, it defaults to port 5000.

πŸ“ Basic Response (Initial Example)

Initially, to demonstrate functionality, a simple HTML response can be sent.

// Inside http.createServer callback
res.statusCode = 200; // HTTP Status Code: OK
res.setHeader('Content-Type', 'text/html'); // Set Content-Type header
res.write('<h1>Hello World!</h1>'); // Write content to the response body
res.end(); // End the response
  • res.statusCode: Sets the HTTP status code. 200 signifies success.

  • res.setHeader(): Sets response headers, such as Content-Type.

  • res.write(): Writes data to the response body.

  • res.end(): Signals the server that all response headers and body have been sent. It must be called for every response.

πŸ’‘ res.writeHead() for Concise Headers

For setting status code and headers more concisely, res.writeHead() can be used:

res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Hello World!</h1>');
  • This combines res.statusCode and res.setHeader() into a single call.

  • res.end() can also directly take the response body.


πŸ› οΈ Request Handling: Routing & Methods

In a vanilla Node.js API, routing and method handling must be done manually by inspecting the req object.

🎣 Accessing Request Details

The req object provides crucial information about the incoming request:

  • req.url: The URL path of the request (e.g., /api/products, /api/products/1).

  • req.method: The HTTP method used (e.g., GET, POST, PUT, DELETE).

🚦 Manual Routing Logic

Conditional statements (if/else if) are used to match specific URLs and HTTP methods.

➑️ GET All Products

To fetch all products, the route is /api/products and the method is GET.

if (req.url === '/api/products' && req.method === 'GET') {
    // Logic to get all products
}

➑️ GET Single Product by ID

To fetch a single product by its ID, the route uses a regular expression to match /api/products/:id and the method is GET. The ID needs to be extracted from the URL.

// Example URL: /api/products/1
if (req.url.match(/\/api\/products\/([0-9]+)/) && req.method === 'GET') {
    // Extract ID:
    const id = req.url.split('/')[3]; // Splits URL by '/' and gets the 3rd index (the ID)
    // Logic to get single product by ID
}
  • req.url.match(): Uses a regular expression to check if the URL conforms to the /api/products/:id pattern.

  • ([0-9]+): Captures one or more digits, representing the product ID.

  • req.url.split('/')[3]: Manually parses the URL to extract the ID.

➑️ POST Create Product

To create a new product, the route is /api/products and the method is POST.

if (req.url === '/api/products' && req.method === 'POST') {
    // Logic to create a new product
}

➑️ PUT Update Product by ID

To update an existing product, the route is /api/products/:id and the method is PUT. The ID needs to be extracted.

if (req.url.match(/\/api\/products\/([0-9]+)/) && req.method === 'PUT') {
    const id = req.url.split('/')[3];
    // Logic to update product by ID
}

➑️ DELETE Product by ID

To delete a product, the route is /api/products/:id and the method is DELETE. The ID needs to be extracted.

if (req.url.match(/\/api\/products\/([0-9]+)/) && req.method === 'DELETE') {
    const id = req.url.split('/')[3];
    // Logic to delete product by ID
}

🚫 Route Not Found (404)

If none of the defined routes match, a 404 Not Found response is sent.

else {
    res.writeHead(404, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ message: 'Route Not Found' }));
}

πŸ›οΈ MVC Architecture: Models & Controllers

To maintain a clean and scalable codebase, the API follows a Model-View-Controller (MVC) design pattern, even though there's no "View" component in a REST API.

πŸ—ΊοΈ models Folder

  • Deals with data interaction. In this API, it interacts with products.json.

  • Model functions handle reading from and writing to the file system.

  • Model functions typically return Promises, simulating asynchronous database operations.

product_model.js

  1. Load Data:

      const products = require('../data/products.json'); // Loads the JSON file
      const { writeDataToFile } = require('../utils'); // Utility to write data
      const { v4: uuidv4 } = require('uuid'); // For generating unique IDs
    • products.json is directly required, which parses it into a JavaScript array of objects.

    • uuidv4 is destructured from uuid to generate version 4 UUIDs.

  2. findAll() - Get All Products:

      function findAll() {
          return new Promise((resolve, reject) => {
              resolve(products); // Simply resolves with the loaded products array
          });
      }
    • Returns a Promise that resolves with the entire products array.

  3. findById(id) - Get Single Product:

      function findById(id) {
          return new Promise((resolve, reject) => {
              const product = products.find((p) => p.id === id); // Finds product by ID
              resolve(product);
          });
      }
    • Uses Array.prototype.find() to locate a product with a matching ID.

  4. create(product) - Create Product:

      function create(product) {
          return new Promise((resolve, reject) => {
              const newProduct = { id: uuidv4(), ...product }; // Assigns a UUID and spreads product data
              products.push(newProduct); // Adds to the in-memory array
              writeDataToFile('./data/products.json', products); // Writes updated array to file
              resolve(newProduct);
          });
      }
    • Generates a unique id using uuidv4().

    • Uses the spread operator (...) to combine the new id with the product data received from the controller.

    • Pushes the newProduct to the in-memory products array.

    • Calls writeDataToFile() (from utils.js) to persist the changes to products.json.

  5. update(id, product) - Update Product:

      function update(id, product) {
          return new Promise((resolve, reject) => {
              const index = products.findIndex((p) => p.id === id); // Finds index of product
              products[index] = { id, ...product }; // Updates product at index, keeping original ID
              writeDataToFile('./data/products.json', products);
              resolve(products[index]); // Resolves with the updated product
          });
      }
    • Uses Array.prototype.findIndex() to get the index of the product to be updated.

    • Replaces the product at that index with the new product data, ensuring the id remains the same.

    • Persists changes to products.json.

  6. remove(id) - Delete Product:

      function remove(id) {
          return new Promise((resolve, reject) => {
              // Filters out the product with the matching ID
              const updatedProducts = products.filter((p) => p.id !== id);
              writeDataToFile('./data/products.json', updatedProducts);
              resolve(); // Resolves without data after deletion
          });
      }
    • Uses Array.prototype.filter() to create a new array excluding the product with the specified id.

    • Writes this updatedProducts array back to the file.

🚦 controllers Folder

  • Handles request-specific logic, interacts with the model, and prepares the response.

  • Controller functions take req and res (and sometimes id) as arguments.

  • They use try-catch blocks for error handling.

product_controller.js

  1. Import Model & Utilities:

      const Product = require('../models/product_model'); // Product Model
      const { getPostData } = require('../utils'); // Utility for POST/PUT body data
  2. getProducts(req, res) - Get All Products:

      async function getProducts(req, res) {
          try {
              const products = await Product.findAll(); // Awaits Promise from model
              res.writeHead(200, { 'Content-Type': 'application/json' });
              res.end(JSON.stringify(products)); // Sends JSON response
          } catch (error) {
              console.log(error);
          }
      }
    • Uses await to handle the Promise returned by Product.findAll().

    • Sets status 200 and Content-Type: application/json.

    • JSON.stringify() is crucial to convert the JavaScript object/array into a JSON string for the response.

  3. getProduct(req, res, id) - Get Single Product:

      async function getProduct(req, res, id) {
          try {
              const product = await Product.findById(id);
              if (!product) { // If product not found
                  res.writeHead(404, { 'Content-Type': 'application/json' });
                  res.end(JSON.stringify({ message: 'Product Not Found' }));
              } else {
                  res.writeHead(200, { 'Content-Type': 'application/json' });
                  res.end(JSON.stringify(product));
              }
          } catch (error) {
              console.log(error);
          }
      }
    • Checks if the product exists; sends 404 if not found, 200 with the product if found.

  4. createProduct(req, res) - Create Product:

      async function createProduct(req, res) {
          try {
              const body = await getPostData(req); // Awaits utility to parse request body
              const { name, description, price } = JSON.parse(body); // Parses JSON string to object
    
              const product = { name, description, price }; // Product data for model
              const newProduct = await Product.create(product); // Awaits model to create
    
              res.writeHead(201, { 'Content-Type': 'application/json' }); // 201 Created
              res.end(JSON.stringify(newProduct));
          } catch (error) {
              console.log(error);
          }
      }
    • Uses getPostData(req) utility to asynchronously read and parse the request body.

    • Destructures name, description, and price from the parsed body.

    • Sends 201 Created status on success.

  5. updateProduct(req, res, id) - Update Product:

      async function updateProduct(req, res, id) {
          try {
              const product = await Product.findById(id);
              if (!product) { // Check if product exists
                  res.writeHead(404, { 'Content-Type': 'application/json' });
                  res.end(JSON.stringify({ message: 'Product Not Found' }));
              } else {
                  const body = await getPostData(req);
                  const { name, description, price } = JSON.parse(body);
    
                  // Allows partial updates: use new value if provided, else keep existing
                  const productData = {
                      name: name || product.name,
                      description: description || product.description,
                      price: price || product.price
                  };
    
                  const updProduct = await Product.update(id, productData); // Awaits model to update
                  res.writeHead(200, { 'Content-Type': 'application/json' });
                  res.end(JSON.stringify(updProduct));
              }
          } catch (error) {
              console.log(error);
          }
      }
    • First, checks if the product to be updated actually exists.

    • Handles partial updates by using || operator: if a field is not provided in the request body, it retains the existing value from the product.

  6. deleteProduct(req, res, id) - Delete Product:

      async function deleteProduct(req, res, id) {
          try {
              const product = await Product.findById(id);
              if (!product) {
                  res.writeHead(404, { 'Content-Type': 'application/json' });
                  res.end(JSON.stringify({ message: 'Product Not Found' }));
              } else {
                  await Product.remove(id); // Awaits model to remove
                  res.writeHead(200, { 'Content-Type': 'application/json' });
                  res.end(JSON.stringify({ message: `Product ${id} removed` }));
              }
          } catch (error) {
              console.log(error);
          }
      }
    • Checks for product existence before attempting to delete.

    • Sends a confirmation message upon successful deletion.

πŸ“¦ Exporting Controller Functions

All controller functions must be exported so they can be imported and used in server.js.

module.exports = {
    getProducts,
    getProduct,
    createProduct,
    updateProduct,
    deleteProduct
};

πŸ”§ Utility Functions (utils.js)

A utils.js file centralizes common helper functions, reducing code duplication.

πŸ’Ύ writeDataToFile(filename, content)

This function handles writing data to a JSON file.

const fs = require('fs'); // Node.js File System module

function writeDataToFile(filename, content) {
    fs.writeFileSync(filename, JSON.stringify(content, null, 4), 'utf8', (err) => {
        if (err) {
            console.log(err);
        }
    });
}
  • fs.writeFileSync(): Writes data to a file synchronously.

  • JSON.stringify(content, null, 4): Converts the JavaScript object content into a JSON string. null, 4 formats the JSON with an indent of 4 spaces for readability.

  • 'utf8': Specifies the file encoding.

πŸ“₯ getPostData(req)

This crucial utility function parses the incoming request body for POST and PUT requests, which is more complex in vanilla Node.js compared to frameworks.

function getPostData(req) {
    return new Promise((resolve, reject) => {
        try {
            let body = '';
            // Event listener for 'data' chunks
            req.on('data', (chunk) => {
                body += chunk.toString(); // Append buffer chunks to body string
            });
            // Event listener for 'end' of request
            req.on('end', () => {
                resolve(body); // Resolve the Promise with the complete body string
            });
        } catch (error) {
            reject(error);
        }
    });
}
  • req.on('data', ...): Listens for data events, which emit chunks of the request body as a Buffer. These chunks are converted to strings and appended to the body variable.

  • req.on('end', ...): Listens for the end event, which signifies that the entire request body has been received. At this point, the complete body string is resolved.

  • This function returns a Promise, allowing async/await to be used in controllers.

πŸ“¦ Exporting Utility Functions

module.exports = {
    writeDataToFile,
    getPostData
};

🏁 Final server.js Structure

The server.js ties everything together, handling routing and delegating tasks to the controllers.

const http = require('http');
const {
    getProducts,
    getProduct,
    createProduct,
    updateProduct,
    deleteProduct
} = require('./controllers/product_controller');

const PORT = process.env.PORT || 5000;

const server = http.createServer((req, res) => {
    // GET /api/products
    if (req.url === '/api/products' && req.method === 'GET') {
        getProducts(req, res);
    }
    // GET /api/products/:id
    else if (req.url.match(/\/api\/products\/([0-9]+)/) && req.method === 'GET') {
        const id = req.url.split('/')[3];
        getProduct(req, res, id);
    }
    // POST /api/products
    else if (req.url === '/api/products' && req.method === 'POST') {
        createProduct(req, res);
    }
    // PUT /api/products/:id
    else if (req.url.match(/\/api\/products\/([0-9]+)/) && req.method === 'PUT') {
        const id = req.url.split('/')[3];
        updateProduct(req, res, id);
    }
    // DELETE /api/products/:id
    else if (req.url.match(/\/api\/products\/([0-9]+)/) && req.method === 'DELETE') {
        const id = req.url.split('/')[3];
        deleteProduct(req, res, id);
    }
    // Route Not Found
    else {
        res.writeHead(404, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ message: 'Route Not Found' }));
    }
});

server.listen(PORT, () => console.log(`Server running on port ${PORT}`));

πŸ§ͺ Testing the API with Postman

Postman (or a similar API client) is essential for testing the different HTTP methods and routes.

πŸ“š CRUD Operations

Operation

Method

URL

Body (JSON) Example

Expected Response

Read All

GET

http://localhost:5000/api/products

None

Array of all products (Status: 200 OK)

Read Single

GET

http://localhost:5000/api/products/1

None

Single product object (Status: 200 OK)

Create

POST

http://localhost:5000/api/products

{"name": "New Product", "description": "...", "price": 123.45}

Newly created product with ID (Status: 201 Created)

Update

PUT

http://localhost:5000/api/<product_id>

{"name": "Updated Name", "price": 99.99}

Updated product object (Status: 200 OK)

Delete

DELETE

http://localhost:5000/api/<product_id>

None

{ "message": "Product <id> removed" } (Status: 200 OK)

Not Found

GET

http://localhost:5000/api/nonexistent

None

{ "message": "Route Not Found" } (Status: 404 Not Found)

⚠️ Key Takeaways for Vanilla Node.js API

  • Manual Routing: Every route and HTTP method combination needs explicit if/else if checks.

  • Body Parsing: Request body data for POST/PUT must be manually collected from req.on('data') and req.on('end') events.

  • JSON Stringification: All JSON responses must be explicitly converted using JSON.stringify().

  • HTTP Headers: Content-Type and Status Code must be manually set for each response.

  • Error Handling: try-catch blocks are essential in asynchronous controller functions.

This vanilla approach provides a foundational understanding of how web servers and APIs function at a low level, highlighting the conveniences offered by frameworks like Express.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent