DEV Community

Cover image for Let’s Develop Shopping Cart for eCommerce App
Nil Madhab
Nil Madhab

Posted on • Edited on

Let’s Develop Shopping Cart for eCommerce App

Every e-Commerce site has a Shopping Cartfeature, today we will learn how to make the backend APIs using Java and Spring Boot

Photo by [Charles Deluvio](https://unsplash.com/@charlesdeluvio?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/online-shopping?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)

Cart is a must-have feature for an e-commerce app that allows the users to save the items they want to buy, change the quantity, and remove them. It should also be able to show the total cost of items in the cart.

We will first develop the back-end API using Java & Spring Boot (in this tutorial). After the API has been created, we will use that API in our Vue.Js front-end(in future tutorials).

Youtube Discussion

Live Demo

You can test the API at the following swagger link. You will find the cart API in cart-controllersection(Run the code in your local first)

Swagger API

You can find the complete code at Github.

Pre-requisites

  1. Knowledge of Java, OOP & Spring Boot Framework

  2. Java Development Kit (JDK)

  3. IntelliJ IDEA Ultimate — open-source (Recommended)

  4. MySQL/MariaDB Database

  5. A good browser (Chrome — recommended)

This tutorial is part of our series on Back-end Development with Java. We will extend the code which we developed in the previous tutorials in this series. So, if you have any doubt regarding anything that we developed earlier, you can read about it in the corresponding tutorial in the series.

Project Structure

If you have not read the previous tutorials in the back-end series, don’t worry. This section is specifically for you. As we will use the project structure that we created in the previous tutorials, we intend to describe the structure here before we begin working on the Wishlist feature. This will help you in understanding the code in a better way.

Following is the project structure:

Project Structure of the API

We will now describe the following directories:-

  1. controller — contains the controllers for various API endpoints

  2. dto — contains the Data Transfer Objects (DTO) for our back-end. In client-server projects, data is often structured differently. There are some details in the database that we do not want to send as a response to the API calls. So, the server stores its information in a database-friendly way. While retrieving that information from the database, it can use DTOs to filter this information and then send it to the client. Don’t worry if you could not understand DTOs. You will understand it when we implement Cart DTO in this tutorial.

  3. model — contains the data models (and entities)

  4. repository — contains the methods for CRUD operations in corresponding tables of the database

  5. service — contains the class files with @service annotations. These class files are used to write business logic in a different layer, separated from @RestController class files. Business logic or domain logic is that part of the program which encodes the real-world business rules that determine how data can be created, stored, and changed inside the database.

  6. exceptions — contains the class files used for throwing exceptions.When we use exceptions, our code becomes much cleaner and more readable.

API Design

Before we begin to code, we must spend some time thinking about the API design and the database design. Let’s begin with the API design.

Currently, we need these API endpoints:-

  1. Adding to cart (POST)

  2. Getting the whole cart (GET)

  3. Update quantity in the cart (PUT)

  4. Delete item from the cart (DELETE)

  1. Adding to cart(POST)

Also, in the body of the POST method, we will have to send the id of the product and the quantity so that the given product can be added to the corresponding user’s cart. Hence, the body of the POST request should look like the following

Post body (if productId is 3 and quantity is 2)

  1. Getting the whole cart (GET)

Now, to get all the items in the cart for a particular user, we need to have a GET request. In return, we will get all the product details, quantity and the total cost of items in the cart. The cartItems is the array of all products present in the cart and the totalCost represents the overall cost of all the items in the cart.

  1. Update the quantity in the cart (PUT)

To update a particular product in the cart, we need the cart_item_id , quantity and user_token .

  1. Delete item from the cart (DELETE)

To delete a particular product from the cart, we need the cart_item_id . We can delete that item by its id.

Table Design

Now, let’s discuss the table design. We had already created the ecommerce database in previous tutorials. In this database, we will create a new table called cart. We will keep the design simple.

The database should have these columns —

  • id is the primary key and will be auto-generated

  • user_id — stores userId

  • product_id — stores the product id

  • quantity — stores the quantity

  • created_date — stores the data & time at which the entry was created

Let’s Code

We will now begin to write code.

Model

Let’s begin with writing the code for the Model class of each entry in the cart table. If you are familiar with Spring Boot or any other MVC framework, you would know that Model class is used to store each entry of the table. In Spring Boot, we use Annotations to map the columns of the table with the class members.

To create the model class, create a new class inside the Cart directory. We will call this class — Cart.

  • We have already described the schema of the table. Using the schema, we will create the class variables of the model class representing each column of the database.

  • We will also create one class object of Product class. This object will store all the details of the product like name, price, description etc.

  • Also, note that the column created_date should be filled with the current date and time. For this, we will use the java.util.Date class.

Following is the complete code of Cart.java


For performing this GET operation, we create another model class named to return the cart items along with the total cost of the cart. The CartCost class contains a list of CartDto and a variable totalCost .This is used to get all cart items.

The CartCost.java is given below —

DTO

By definition, DTO or Data Transfer Objects is an object that carries data between processes. DTO lets us hide our entity from a client who is using that API and code maintenance becomes easier if we want to change our internal database structure. We only expose that part of the entity which the user should be able to edit.

We will use the CartDto for showing cart data. We will also create AddToCartDto so that we can add/update products into the cart because we only need userId,cartItemId,productId,quantity for these 2 processes.

The CartDto.java class is given below —


The AddToCartDto is given below.

Repository

It is time to create the repository interface for the Cart table.Create a new file called CartRepository.java inside the Repository directory.

If you are familiar with Spring Boot, you would know that Repository the interface contains methods to fetch data from the table.

Creating CRUD methods manually means writing a lot of boilerplate code unless you let the JPARepository interface carry about routine implementations for you. So, we will extend the JPARepository and create the interface CartRepository.

  • Extending JPARepository will automatically create and implement methods for the basic CRUD operations.

  • We will define a method findAllByUserIdOrderByCreatedDateDesc() to fetch the cart of a user and order the list by created the date of each entry in the cart. The implementation of this method will be managed automatically by the JPARepository .

Following is the complete code of CartRepository.java

Exceptions

Before dealing with the Service and Controller, we will talk about Exceptions. If we find wrong token or wrong product id , we can throw exceptions. Here we will create AuthenticationFailException , CartItemNotExistException , ProductNotExistException . The code is simple for the exception. I am listing the code for AuthenticationFailException , other exception classes are the same.

Service

Now, let’s implement the Service class to interact with the carttable. In the CartRepository interface, we defined the methods to interact with the database.

In the Service class, we will call these methods and implement the so-called business logic. We will create methods for add, get, update and delete to the cart. Inside these methods, we will call the methods defined in the CartRepositoryinterface.

Following is the complete code of CartService.java


In the listCartItems , we calculate the total cost of all the items in the cart and store it in a variable. We return the response as CartCost such that it contains the list of products in the cart and it’s total cost.

Controller

Now, Let’s begin with writing code for the controller. If you are familiar with Spring Boot or any other MVC framework, you would already know that controller defines the endpoints of the API.

Create a new file inside the Controller directory with the name CartController.java . Since we have 4 endpoints, we will create four methods in the CartController class.

  • To use the Cartservice and AuthenticationService , we will create the two objects of respective types. We have already created the Cartservicein the previous section and is used to interact with the database. We created AuthenticationService in a previous tutorial and is used to fetch the user id of the corresponding token. We will also check whether the token is correct or not.

The following is the complete code of CartController.java


Also, remember to add this code section to the ProductService , if not it will throw an error.

Congratulations!!!

Congratulations, we have now added the cart feature to our backend.

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

Get our code from this repository.

ecommerce

Ecommerce backend apis

Backend https://github.com/webtutsplus/ecommerce-backend

https://limitless-lake-55070.herokuapp.com/swagger-ui.html

Frontend

https://github.com/webtutsplus/ecommerce-vuejs

https://infallible-swartz-b50174.netlify.app/

  • This is a Maven Project. Ensure, Maven is installed on your system.
  • It is Recommended that you use Linux Based OS.
  • It might happen that you have installed XAMPP/LAMPP software (by Bitnami) on your system. Instead of using the db provided by XAMPP/LAMPP by bitnami, it is recommended that you install mariadb-server and use it as database while running this application.

###How to run in local

  1. Rename src/main/resources/application.properties.example to src/main/resources/application.properties.
  2. Change the Application Properties (E.g. username/password of DB) present in resources/application.properties according to your local mysql-server.
  3. Go to application.properties and comment / uncomment the corresponding front-end url and enter the STRIPE API Keys
  4. Create a database called ecommerce with CHARACTER SET utf8mb4 and COLLATE utf8mb4_0900_ai_ci. MariaDB does not support COLLATE utf8mb4_0900_ai_ci. So, if you are using MariaDB, open database-dump.sql file and replace COLLATE utf8mb4_0900_ai_ci with COLLATE utf8mb4_general_ci

Top comments (1)

Collapse
 
zvmichalsa89s profile image
Michal Sa

Wax or sealants are used to car detailing supplies protect the paint from UV rays, moisture, and contaminants, allowing it to retain its sheen and prevent damage.