forbestheatreartsoxford.com

Creating a Shopping Cart for an eCommerce Application

Written on

Every e-commerce platform includes a shopping cart feature. In this guide, we will explore how to create backend APIs utilizing Java and Spring Boot.

A shopping cart is essential for any e-commerce application, enabling users to save their desired items, adjust quantities, or remove products. Additionally, it should display the total price of the items within the cart.

Initially, we will construct the backend API with Java and Spring Boot (as outlined in this tutorial). Once the API is operational, we will integrate it with our Vue.js frontend in subsequent tutorials.

If you're interested in supporting my work and gaining access to more content, consider becoming a member of Medium for just $5/month.

Comprehensive Guide to Building an E-Commerce Platform

We will develop an e-commerce platform from the ground up using Vue.js and the Spring Framework.

YouTube Tutorial Playlist

Frontend Backend

YouTube Discussion

Frontend Tutorial

Adding a Shopping Cart Feature in Vue.js for Our E-Commerce App In this tutorial, we will learn how to display, update, and remove items from our shopping cart in the demo e-commerce application.

[Read more here](https://javascript.plainenglish.io)

Prerequisites

  1. Understanding of Java, OOP, and the Spring Boot Framework
  2. Java Development Kit (JDK)
  3. IntelliJ IDEA Ultimate (Recommended)
  4. MySQL/MariaDB Database
  5. A capable web browser (Chrome is recommended)

This tutorial is part of our series on backend development with Java. We will build on the code established in previous tutorials within this series. If you have questions about earlier content, please refer to the corresponding tutorial.

Project Structure

If you haven't gone through the previous tutorials in this backend series, don't worry. This section will guide you through the project structure we will use for the Wishlist feature, facilitating a better understanding of the code.

The project structure is as follows:

We will describe the following directories: 1. controller — hosts the controllers for various API endpoints. 2. dto — contains Data Transfer Objects (DTO) for our backend. In client-server projects, data is often structured differently. Certain database details may not be included in API responses. Thus, the server organizes data in a database-friendly manner and uses DTOs to filter this information for the client. Don’t worry if you find DTOs confusing; you will grasp it as we implement the Cart DTO in this tutorial. 3. model — includes data models (and entities). 4. repository — holds methods for CRUD operations on the database tables. 5. service — contains class files annotated with @service. These files are used to implement business logic in a separate layer from @RestController class files. Business or domain logic represents the real-world rules that dictate how data can be created, stored, and modified within the database. 6. exceptions — includes class files for throwing exceptions, improving code clarity and readability.

API Design

Before diving into coding, we need to consider the API and database designs.

Currently, we require the following API endpoints: 1. Add to cart (POST) 2. Retrieve the entire cart (GET) 3. Update item quantity in the cart (PUT) 4. Remove an item from the cart (DELETE)

  1. Adding to cart (POST)

    In the body of the POST request, include the product ID and the quantity so that the specified product can be added to the user's cart. The body should look like this:

  2. Retrieving the whole cart (GET)

    To get all items in a user's cart, we will initiate a GET request. This will return all product details, quantities, and the total cost. The response will include an array of all products in the cart along with the total cost.

  3. Updating the quantity in the cart (PUT)

    To modify a specific product in the cart, we need the cart_item_id, quantity, and user_token.

  4. Removing an item from the cart (DELETE)

    To delete a specific product from the cart, we will require the cart_item_id, which allows us to remove the item by its ID.

Table Design

Now, let's delve into the table design. The ecommerce database was created in prior tutorials. In this database, we will establish a new table called cart with a simple design.

The table will consist of the following columns: - id: the primary key, auto-generated - user_id: stores the user ID - product_id: stores the product ID - quantity: stores the quantity - created_date: records the date and time when the entry was created

Let's Code

We will now start writing the code.

Model

We will begin with creating the model class for each entry in the cart table. If you're familiar with Spring Boot or similar MVC frameworks, you know that the model class is utilized to represent each table entry. Annotations are used in Spring Boot to map the table columns to class members.

To create the model class, create a new class in the Cart directory and name it Cart.

  • We will create class variables based on the schema we defined earlier, representing each column in the database.
  • Additionally, we will create an object of the Product class to store details like name, price, description, etc.
  • The created_date column will be assigned the current date and time using java.util.Date.

The complete code for Cart.java is as follows:

// Code for Cart.java goes here

For the GET operation, we will create another model class to return the cart items along with the total cost. The CartCost class will include a list of CartDto and a totalCost variable to represent all cart items.

The CartCost.java code is as follows:

// Code for CartCost.java goes here

DTO

Data Transfer Objects (DTO) are objects that carry data between processes. They allow us to conceal our entity from clients accessing the API, simplifying code maintenance if we need to alter our internal database structure. We expose only the parts of the entity that users should edit.

We will utilize the CartDto for displaying cart data and create AddToCartDto for adding/updating products in the cart, requiring only userId, cartItemId, productId, and quantity for these operations.

The CartDto.java class is as follows:

// Code for CartDto.java goes here

The AddToCartDto is defined as:

// Code for AddToCartDto.java goes here

Repository

Next, we will establish the repository interface for the cart table. Create a new file named CartRepository.java inside the Repository directory.

If you're familiar with Spring Boot, you know that the Repository interface encompasses methods to retrieve data from the table.

To reduce boilerplate code, we will extend the JPARepository, creating the CartRepository interface.

  • Extending JPARepository will automatically create and implement methods for basic CRUD operations.
  • We will define the method findAllByUserIdOrderByCreatedDateDesc() to fetch a user's cart, ordering the list by the entry's created date.

The complete code for CartRepository.java is as follows:

// Code for CartRepository.java goes here

Exceptions

Before addressing the Service and Controller layers, let's discuss exceptions. We can throw exceptions for incorrect tokens or product IDs. We will create AuthenticationFailException, CartItemNotExistException, and ProductNotExistException. Here’s the code for the AuthenticationFailException; the other classes follow a similar structure.

// Code for AuthenticationFailException.java goes here

Service

Now, let's implement the Service class to interact with the cart table. In the CartRepository interface, we defined methods for database interaction.

In the Service class, we will invoke these methods to implement business logic. Methods for adding, retrieving, updating, and deleting items in the cart will be created, calling the methods defined in the CartRepository interface.

The complete code for CartService.java is as follows:

// Code for CartService.java goes here

In the listCartItems method, we compute the total cost of all items in the cart and return the response as CartCost, which includes the list of products and their total cost.

Controller

Now, we will write the code for the controller. If you're familiar with Spring Boot or similar MVC frameworks, you know that the controller defines the API endpoints.

Create a new file in the Controller directory named CartController.java. Since we have four endpoints, we will implement four methods in the CartController class.

  • We will create two objects for CartService and AuthenticationService. The CartService interacts with the database, while the AuthenticationService retrieves the user ID corresponding to the token and verifies its validity.

The complete code for CartController.java is as follows:

// Code for CartController.java goes here

Also, ensure this code section is included in the ProductService; otherwise, it may cause errors.

// Additional code for ProductService.java goes here

Congratulations!!!

Congratulations! We have successfully integrated the cart feature into our backend.

In the next tutorial, we will implement the Vue.js frontend and connect it with our backend.

You can find our code in this repository:

[webtutsplus/ecommerce-backend](https://github.com/webtutsplus/ecommerce-backend)

Ecommerce backend APIs. This is a Maven project; ensure Maven is installed on your system. It is recommended that you…

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

# March Mastery: Exceptional Articles and Insights from Better Humans

Discover outstanding articles from March and insights behind Better Humans' editorial changes aimed at enhancing quality.

Calculating Distances to Nearby Stars: Understanding Stellar Parallax

Explore how stellar parallax allows us to measure distances to nearby stars, revealing our cosmic location.

Evil Grin: A Deep Dive into Darkness and Despair

An exploration of the 'Evil Grin' phenomenon, its impact, and the dark motivations behind it.

# Lessons from Astronauts on Healthy Living: Insights for Earthlings

Discover valuable health insights from astronauts and learn how to apply them to your daily routine.

Embracing Simplicity: The Art of Clear Writing

Discover the importance of simplicity in writing and communication, and learn strategies to achieve clarity.

Unraveling the Last Coconut Puzzle: A Test of Intuition

Explore the intriguing Last Coconut Puzzle and discover the probabilities involved in decision-making.

Revolutionizing Quantum Computing: The Multi-Chip Breakthrough

A look at Rigetti's game-changing multi-chip quantum processor and its implications for the future of quantum computing.

The Crucial Role of Data in Data Science Projects

Explore why data preparation is vital in data science, encompassing its challenges and significance in decision-making.