Developing a Basic E-commerce Backend API with Node.js and MySQL

In the digital era, e-commerce has revolutionized the way we shop, offering convenience and accessibility to consumers worldwide. Behind the scenes of every successful online store lies a robust and efficient backend infrastructure that handles crucial tasks such as managing products, processing orders, and handling user interactions. In this comprehensive guide, we’ll explore how to build a dynamic e-commerce backend using Node.js and MySQL, empowering you to create scalable and feature-rich online shopping experiences.

Setting Up the Project:

We kickstart our journey by setting up the project structure and installing necessary dependencies. With a few simple commands, we initialize a Node.js project and install Express, a minimalist web framework for Node.js, along with MySQL, a popular relational database management system.

Let’s kick off our journey by setting up the project structure and installing the necessary dependencies. Open your terminal and follow along with these commands:

    
     mkdir ecommerce-backend
cd ecommerce-backend
npm init -y
npm install express mysql2 body-parser
    
   

We’re using npm to initialize a new Node.js project and install key dependencies such as Express (a minimalist web framework for Node.js), MySQL2 (a MySQL client for Node.js), and body-parser (a middleware to parse incoming request bodies).

 

Creating the MySQL Database:

Next, we delve into the database setup, a critical component of any e-commerce backend. We create a MySQL database named ‘ecommerce’ and define tables for storing product, category, and cart data. Each table is meticulously designed to capture essential information such as product details, category attributes, and user cart items.

A robust database is essential for storing and managing product, category, and user data. Let’s create a MySQL database named ‘ecommerce’ and define tables for our e-commerce platform:

    
     CREATE DATABASE ecommerce;

USE ecommerce;

CREATE TABLE products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    price DECIMAL(10, 2) NOT NULL,
    stock INT NOT NULL,
    category_id INT NOT NULL,
    image_url VARCHAR(255),
    discount_price DECIMAL(10, 2)
);

CREATE TABLE categories (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    image_url VARCHAR(255)
);

CREATE TABLE cart (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    product_id INT NOT NULL,
    quantity INT NOT NULL,
    FOREIGN KEY (user_id) REFERENCES users(id),
    FOREIGN KEY (product_id) REFERENCES products(id)
);

    
   

These SQL commands create the ‘ecommerce’ database and define three tables: ‘products’ to store product details, ‘categories’ to store category information, and ‘cart’ to manage user shopping carts.

 

Setting Up the Express Server:

With the groundwork laid, we proceed to set up the Express server, the heart of our backend application. We establish a connection to the MySQL database and configure routes to handle incoming HTTP requests. Express provides a streamlined way to define endpoints for creating, retrieving, updating, and deleting resources such as products, categories, and cart items.

Now, let’s create a file named server.js and set up our Express server along with the database connection:

    
     const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql2');

const app = express();
const port = 3000;

app.use(bodyParser.json());

const db = mysql.createConnection({
  host: 'localhost',
  user: 'your_mysql_username',
  password: 'your_mysql_password',
  database: 'ecommerce'
});

db.connect((err) => {
  if (err) {
    console.error('Error connecting to MySQL database: ' + err.stack);
    return;
  }
  console.log('Connected to MySQL database as id ' + db.threadId);
});

// Define Routes

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

    
   

This code sets up an Express server listening on port 3000 and establishes a connection to the MySQL database using the mysql2 package. We’ve also configured body-parser middleware to parse incoming JSON requests.

 

Implementing Product and Category Endpoints:

Our journey continues as we implement endpoints for managing products and categories. These endpoints allow us to perform various operations such as creating new products, retrieving product details, updating existing products, and deleting products that are no longer needed. Similarly, we provide endpoints for handling categories, enabling seamless management of product categories within our e-commerce platform.

Implementing Product Endpoints:

Let’s start by implementing endpoints for managing products. Add the following code to server.js:

    
     // Create Product
app.post('/products', (req, res) => {
  const { name, description, price, stock, category_id, image_url, discount_price } = req.body;
  const sql = 'INSERT INTO products (name, description, price, stock, category_id, image_url, discount_price) VALUES (?, ?, ?, ?, ?, ?, ?)';
  db.query(sql, [name, description, price, stock, category_id, image_url, discount_price], (err, result) => {
    if (err) {
      res.status(500).send('Error creating product');
      return;
    }
    res.status(201).send('Product created successfully');
  });
});

// Get All Products
app.get('/products', (req, res) => {
  db.query('SELECT * FROM products', (err, results) => {
    if (err) {
      res.status(500).send('Error retrieving products');
      return;
    }
    res.json(results);
  });
});

// Get Products by Category
app.get('/products', (req, res) => {
  const categoryId = req.query.category_id; // Retrieve category_id from query params
  let sql = 'SELECT * FROM products';

  // If category_id is provided, filter products by category
  if (categoryId) {
    sql += ' WHERE category_id = ?';
    db.query(sql, [categoryId], (err, results) => {
      if (err) {
        res.status(500).send('Error retrieving products by category');
        return;
      }
      res.json(results);
    });
  } else {
    db.query(sql, (err, results) => {
      if (err) {
        res.status(500).send('Error retrieving products');
        return;
      }
      res.json(results);
    });
  }
});

// Update Product
app.put('/products/:id', (req, res) => {
  const productId = req.params.id;
  const { name, description, price, stock, category_id, image_url, discount_price } = req.body;
  const sql = 'UPDATE products SET name=?, description=?, price=?, stock=?, category_id=?, image_url=?, discount_price=? WHERE id=?';
  db.query(sql, [name, description, price, stock, category_id, image_url, discount_price, productId], (err, result) => {
    if (err) {
      res.status(500).send('Error updating product');
      return;
    }
    res.status(200).send('Product updated successfully');
  });
});

// Delete Product
app.delete('/products/:id', (req, res) => {
  const productId = req.params.id;
  const sql = 'DELETE FROM products WHERE id=?';
  db.query(sql, [productId], (err, result) => {
    if (err) {
      res.status(500).send('Error deleting product');
      return;
    }
    res.status(200).send('Product deleted successfully');
  });
});


    
   

These routes handle CRUD (Create, Read, Update, Delete) operations for products. We’ll implement the logic for each endpoint shortly.

 

Implementing Category Endpoints:

Next, let’s implement endpoints for managing product categories:

    
     // Create Category
app.post('/categories', (req, res) => {
  const { name, description, image_url } = req.body;
  const sql = 'INSERT INTO categories (name, description, image_url) VALUES (?, ?, ?)';
  db.query(sql, [name, description, image_url], (err, result) => {
    if (err) {
      res.status(500).send('Error creating category');
      return;
    }
    res.status(201).send('Category created successfully');
  });
});

// Get All Categories
app.get('/categories', (req, res) => {
  db.query('SELECT * FROM categories', (err, results) => {
    if (err) {
      res.status(500).send('Error retrieving categories');
      return;
    }
    res.json(results);
  });
});

// Update Category
app.put('/categories/:id', (req, res) => {
  const categoryId = req.params.id;
  const { name, description, image_url } = req.body;
  const sql = 'UPDATE categories SET name=?, description=?, image_url=? WHERE id=?';
  db.query(sql, [name, description, image_url, categoryId], (err, result) => {
    if (err) {
      res.status(500).send('Error updating category');
      return;
    }
    res.status(200).send('Category updated successfully');
  });
});

// Delete Category
app.delete('/categories/:id', (req, res) => {
  const categoryId = req.params.id;
  const sql = 'DELETE FROM categories WHERE id=?';
  db.query(sql, [categoryId], (err, result) => {
    if (err) {
      res.status(500).send('Error deleting category');
      return;
    }
    res.status(200).send('Category deleted successfully');
  });
});


    
   

These routes allow us to perform CRUD operations on product categories, similar to the product endpoints.

 

Implementing Cart Endpoints:

No e-commerce platform is complete without a robust shopping cart feature. In this section, we focus on implementing endpoints to manage user shopping carts. Users can add products to their cart, view the contents of their cart, update quantities, and remove items as needed. By leveraging the power of Node.js and MySQL, we ensure a smooth and intuitive shopping experience for our users.

Finally, let’s add endpoints for managing user shopping carts.

    
     // Add Product to Cart
app.post('/cart/add', (req, res) => {
  const { user_id, product_id, quantity } = req.body;
  const sql = 'INSERT INTO cart (user_id, product_id, quantity) VALUES (?, ?, ?)';
  db.query(sql, [user_id, product_id, quantity], (err, result) => {
    if (err) {
      res.status(500).send('Error adding product to cart');
      return;
    }
    res.status(201).send('Product added to cart successfully');
  });
});

// Get Cart Products by User ID
app.get('/cart/:user_id', (req, res) => {
  const userId = req.params.user_id;
  const sql = 'SELECT cart.*, products.name, products.price FROM cart INNER JOIN products ON cart.product_id = products.id WHERE cart.user_id = ?';
  db.query(sql, [userId], (err, results) => {
    if (err) {
      res.status(500).send('Error retrieving cart products');
      return;
    }
    res.json(results);
  });
});

// Update Cart Item
app.put('/cart/:id', (req, res) => {
  const cartItemId = req.params.id;
  const { quantity } = req.body;
  const sql = 'UPDATE cart SET quantity=? WHERE id=?';
  db.query(sql, [quantity, cartItemId], (err, result) => {
    if (err) {
      res.status(500).send('Error updating cart item');
      return;
    }
    res.status(200).send('Cart item updated successfully');
  });
});

// Delete Cart Item
app.delete('/cart/:id', (req, res) => {
  const cartItemId = req.params.id;
  const sql = 'DELETE FROM cart WHERE id=?';
  db.query(sql, [cartItemId], (err, result) => {
    if (err) {
      res.status(500).send('Error deleting cart item');
      return;
    }
    res.status(200).send('Cart item deleted successfully');
  });
});

    
   

These routes handle operations related to user shopping carts, allowing users to add, view, update, and remove items from their cart.

 

Testing and Conclusion:

With our backend API implemented, it’s essential to thoroughly test each endpoint to ensure functionality and reliability. Tools like Postman can be used to send HTTP requests and verify responses.

In conclusion, building a dynamic e-commerce backend with Node.js and MySQL empowers developers to create scalable and feature-rich online shopping experiences. By following this step-by-step guide, you’ve gained the knowledge and tools necessary to build a powerful backend API to support your e-commerce platform. Happy coding!

Note: Don’t forget to replace ‘your_mysql_username’ and ‘your_mysql_password’ with your actual MySQL credentials before running the server.

👋 Hey There!

Need a hand with web development? Whether it’s a bug that’s giving you a headache, a design dilemma, or you just want to chat about making your website shine, we’re here for you!

Shoot us a message with the details, and we’ll get back to you faster than you can say “HTML.” Let’s turn your web dreams into reality together! 💻✨

Please enable JavaScript in your browser to complete this form.
Name