Every e-Commerce site has a Shopping Cartfeature, today we will learn how to make the backend APIs using Java and Spring Boot
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.
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)
You can find the complete code at Github.
Knowledge of Java, OOP & Spring Boot Framework
Java Development Kit (JDK)
IntelliJ IDEA Ultimate — open-source (Recommended)
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.
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:-
controller — contains the controllers for various API endpoints
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.
model — contains the data models (and entities)
repository — contains the methods for CRUD operations in corresponding tables of the database
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.
exceptions — contains the class files used for throwing exceptions.When we use exceptions, our code becomes much cleaner and more readable.
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:-
Adding to cart (POST)
Getting the whole cart (GET)
Update quantity in the cart (PUT)
Delete item from the cart (DELETE)
- 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
- 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.
- 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 .
- 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.
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
We will now begin to write code.
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 —
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.
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
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.
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.
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, 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 backend apis
- 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-serverand use it as database while running this application.
###How to run in local
- Change the Application Properties (E.g. username/password of DB) present in
resources/application.propertiesaccording to your local mysql-server.
- Go to application.properties and comment / uncomment the corresponding front-end url
- Create a database called
CHARACTER SET utf8mb4and
COLLATE utf8mb4_0900_ai_ci. MariaDB does not support
COLLATE utf8mb4_0900_ai_ci. So, if you are using MariaDB, open
database-dump.sqlfile and replace
- To run the application, run the command
sh run.shi.e. execute the