Let’s Develop Shopping Cart for eCommerce App
Tags: ecommerce, backend
Published: 2021-02-25 06:15:16

Every e-Commerce site has a **Shopping Cart**feature, 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)](https://cdn-images-1.medium.com/max/3840/1*RBpW8CIMl7R8q9xbOSjvtg.jpeg)

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 ](https://medium.com/javarevisited/10-books-java-developers-should-read-in-2020-e6222f25cc72)& [Spring Boot](https://medium.com/javarevisited/top-10-courses-to-learn-spring-boot-in-2020-best-of-lot-6ffce88a1b6e?source=---------39------------------) (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
{% youtube RgWm5GB8fLo %}
## 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**](http://localhost:8080/api/swagger-ui.html#/)

You can find the complete code at [Github](https://github.com/webtutsplus/ecommerce-backend).

## Pre-requisites

 1. Knowledge of Java, [OOP ](https://medium.com/javarevisited/my-favorite-courses-to-learn-object-oriented-programming-and-design-in-2019-197bab351733)& Spring Boot Framework

 2. Java Development Kit (JDK)

 3. [IntelliJ IDEA Ultimate](https://www.jetbrains.com/idea/download/) — open-source (Recommended)

 4. [MySQL](https://medium.com/javarevisited/top-5-courses-to-learn-mysql-in-2020-4ffada70656f)/MariaDB Database

 5. A good browser (Chrome — recommended)

This tutorial is part of our series on [Back-end Development with Java](https://nilmadhab.medium.com/). 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:

![](https://cdn-images-1.medium.com/max/2000/1*OJRN72-B8dT2q-KhXyp_xw.png)

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](https://javarevisited.blogspot.com/2013/01/data-access-object-dao-design-pattern-java-tutorial-example.html#axzz5b2noKDk3) (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](https://medium.com/hackernoon/top-5-sql-and-database-courses-to-learn-online-48424533ac61), 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](http://en.wikipedia.org/wiki/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](https://medium.com/javarevisited/5-best-books-to-learn-sql-and-database-design-for-programmers-and-developers-1e7839df2f3e). 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)

![](https://cdn-images-1.medium.com/max/2154/1*U7NA5E-IJmiVC_D_1kP3YQ.png)

 1. **Adding to cart(POST)**

Also, in the body of the [POST method](https://javarevisited.blogspot.com/2012/03/get-post-method-in-http-and-https.html), 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)](https://cdn-images-1.medium.com/max/2000/1*S9jxjsAZ3oVyLV7Uf7Fxog.png)

2. **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.

![](https://cdn-images-1.medium.com/max/2800/1*9DJ0eG0cgAjM6hGXW1WkMg.png)

3. **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 .

4. **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](https://medium.com/javarevisited/10-free-spring-boot-tutorials-and-courses-for-java-developers-53dfe084587e?source=collection_home---4------7-----------------------) or any other MVC framework, you would know that Model class is used to store each entry of the table. In [Spring Boot](https://medium.com/hackernoon/top-5-spring-boot-and-spring-cloud-books-for-java-developers-75df155dcedc), 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
{% gist https://gist.github.com/sksaikia/be34d5ab29217259c0d5149622e6fec7.js %}
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 —
{% gist https://gist.github.com/sksaikia/b6f4a4e31b72ab44b8fb50067f8facad.js %}
## **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 —
{% gist https://gist.github.com/sksaikia/6c4e5c68b7aec8680a056ab625300833.js %}
The AddToCartDto is given below.
{% gist https://gist.github.com/sksaikia/4e7a39cee4766e883f7b590266f99c2e.js %}
## 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](https://medium.com/javarevisited/10-best-java-microservices-courses-with-spring-boot-and-spring-cloud-6d04556bdfed), 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
{% gist https://gist.github.com/sksaikia/deba4bd25b4ca0cd75fa37bb0ba83079.js %}
## **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.
{% gist https://gist.github.com/sksaikia/b6e6f6507c1fe1ac9ce9404cc6d9ee17.js %}
## **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
{% gist https://gist.github.com/sksaikia/3ee374594dcf8b2a6b70c05a968e3791.js %}
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](https://www.java67.com/2017/11/top-5-free-core-spring-mvc-courses-learn-online.html) or any other [MVC framework](https://medium.com/javarevisited/21-spring-mvc-rest-interview-questions-answers-for-beginners-and-experienced-developers-21ad3d4c9b82), 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
{% gist https://gist.github.com/sksaikia/41518622c1edafb6e3999b0df80ae644.js %}
Also, remember to add this code section to the ProductService , if not it will throw an error.
{% gist https://gist.github.com/sksaikia/b15a68bff282289a8d77aabc5848a29b.js %}
## 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.
{% github webtutsplus/ecommerce-backend %}