0% found this document useful (0 votes)
64 views10 pages

Le Kim Ngan NCKH FIT 2025

This study focuses on developing a RESTful API for an online shopping cart application using Spring Boot MVC, emphasizing design principles for consistency and scalability. It details the API development process, including architectural design, data modeling, and CRUD endpoint implementation, while employing Postman for testing to ensure API stability. The research aims to address key questions regarding RESTful API concepts and effective implementation in Java web applications.

Uploaded by

kle27512
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views10 pages

Le Kim Ngan NCKH FIT 2025

This study focuses on developing a RESTful API for an online shopping cart application using Spring Boot MVC, emphasizing design principles for consistency and scalability. It details the API development process, including architectural design, data modeling, and CRUD endpoint implementation, while employing Postman for testing to ensure API stability. The research aims to address key questions regarding RESTful API concepts and effective implementation in Java web applications.

Uploaded by

kle27512
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

XÂY DỰNG GIỎ HÀNG TRỰC TUYẾN THEO KIẾN

TRÚC RESTFUL API VỚI SPRING BOOT


Lê Kim Ngân - 6C22

GVHD: Ngô Văn Quyền

Tóm tắt: Trong phát triển Java Web, RESTful API đóng vai trò quan trọng trong việc xây
dựng các hệ thống backend linh hoạt và dễ mở rộng. Bài nghiên cứu này tập trung vào quá
trình phát triển RESTful API cho một ứng dụng giỏ hàng trực tuyến sử dụng Spring Boot MVC,
tuân theo nguyên tắc thiết kế REST để đảm bảo tính nhất quán, khả năng mở rộng và dễ dàng
tích hợp với các hệ thống frontend khác. Nghiên cứu trình bày các bước quan trọng trong quá
trình xây dựng API, bao gồm thiết kế kiến trúc, mô hình dữ liệu, triển khai các endpoint CRUD
cho sản phẩm, giỏ hàng, đơn hàng và người dùng. Song song với đó phương pháp thử nghiệm
bằng Postman cũng được thực hiện để đảm bảo API hoạt động ổn định, nhằm giải quyết các
câu hỏi nghiên cứu của bài.

Từ khóa: RESTful API; Spring Boot; giỏ hàng trực tuyến.

BUILDING ONLINE SHOPPING CART ACCORDING


TO RESTFUL API ARCHITECTURE WITH SPRING
BOOT

Abstract: In Java web development, RESTful APIs play a crucial role in building flexible
and scalable backend systems. This study focuses on the development of a RESTful API for an
online shopping cart application using Spring Boot MVC, adhering to REST design principles to
ensure consistency, scalability, and seamless integration with various frontend systems. The
research outlines key steps in the API development process, including architectural design,
data modeling, and the implementation of CRUD endpoints for products, shopping carts, orders,
and users. Additionally, testing with Postman is conducted to ensure the API's stability,
addressing the research questions of this study.

Keywords: RESTful API; Spring Boot MVC; online shopping cart.

1. Introduction
The Spring Framework (Spring) is a modular, open-source application
framework that provides infrastructure support for developing Java applications.
Spring, one of the most popular Java Enterprise Edition (Java EE) frameworks,
allows developers to create scalable and high-performance applications using
simple Java objects (POJOs) (B. Kahit et al., 2020). Its flexibility and support for
various architectures, including microservices, make it an ideal choice for
building RESTful APIs. RESTful API development plays a crucial role in
modern web applications, enabling seamless communication between client and
server while ensuring scalability and maintainability. In the context of e-
commerce, a well-structured RESTful API is essential for handling product
management, shopping cart operations, and order processing efficiently.
This study focuses on the development of a Shopping Cart API using Spring
Boot MVC, following RESTful design principles. The goal is to ensure
consistency, scalability, and ease of integration with frontend applications.
The study tries to resolve certain research questions about RESTful API
development for shopping cart applications. There are two main research
questions:
(1) What is the concept of RESTful API when building Java web
applications with Spring Boot MVC?
(2) How to implement a RESTful API for an online shopping cart
system effectively?
To address these issues, the study conducts an analysis of the core
architectural components, data models, and API endpoints of the shopping cart
system. The Postman tool is utilized to test the APIs, ensuring consistency and
accuracy in interactions with the system database.
This paper is structured into three main sections. The Introduction provides
an overview of RESTful API development, the research questions, and the
methodology. The Understanding and Case Study section includes a literature
review of RESTful principles and a case study on implementing a shopping cart
API using Spring Boot. The Conclusion summarizes the research findings and
provides recommendations for improving API scalability and performance.
2. Understanding and Case Study
2.1. Background and literature review
2.1.1. Fundamentals of API
An API (Application Programming Interface) in Spring Boot is a set of
conventions and protocols that allows different software systems to communicate
with each other. Spring Boot, a Java-based framework, simplifies the process of
creating production-ready APIs by providing a set of pre-configured templates
and tools for building RESTful APIs quickly and efficiently.
A fundamental Spring Boot API follows REST principles, enabling it to
communicate effectively over HTTP with a variety of clients such as web
applications, mobile apps, and other services. Here are the key aspects of
building APIs in Spring Boot: Spring Boot Setup, RESTful Design, Controllers,
Request and Response Handling, Model and Entity Classes, Exception Handling,
Security, Swagger Integration, Testing. By following these principles and
practices, Spring Boot APIs are efficient, maintainable, and scalable, ensuring
that the applications are easy to develop and deploy while adhering to industry
standards for API design and communication.
2.1.2. RESTful API definition and components
REST (Representational State Transfer) is a data structure conversion and an
architectural style for writing APIs. A RESTful API is a standard used in
designing APIs for web applications to manage resources. It uses simple HTTP
methods to facilitate communication between machines. Instead of using a single
URL for processing user information, REST sends an HTTP request to a URL to
process data. REST APIs work by sending requests and receiving responses,
typically in JSON format, between the client and server.
In the Controller layer, REST API call types and endpoints are specified
using annotations like @GetMapping, @PostMapping, @PutMapping, and
@DeleteMapping. These methods handle client requests, data retrieval from the
repository, and result returns, with common methods like save, findAll, findById,
and findByFirstName (I. Jraset et al., 2023). The project is executed, and testing
involves sending HTTP requests with specified methods, URIs, and request
bodies, receiving JSON responses with accompanying HTTP status codes. The
fundamental operations mentioned above use specific HTTP methods, commonly
referred to as CRUD (Create, Read, Update, Delete), specifically GET (read-only
resource access), POST (new resource creation), DELETE (resource deletion),
and PUT (resource update)
(1) The GET method is used to read (or retrieve) a representation of a
resource. If successful, it returns a response in XML or JSON format along
with an HTTP 200 (OK) status code. In case of an error, it typically returns
404 (NOT FOUND) or 400 (BAD REQUEST).
(2) The POST method is mainly used to create new resources,
especially subordinate resources. When a new resource is successfully
created, the server responds with HTTP 201 (CREATED) and includes a
Location header pointing to the newly created resource.
(3) The PUT method is used to update or create a resource on the
server. It requires sending the entire resource in the request body, replacing
the existing resource at the specified URL. If the resource does not exist, PUT
can create a new one.
(4) The DELETE method is used to remove a resource identified by a
URI. Upon successful deletion, the server typically returns an HTTP 200
(OK) response, optionally including a response body.
2.1.3. Literature review
The Spring Framework has become a cornerstone in Java-based web
development due to its modular architecture, dependency injection (IoC), and
robust MVC design pattern (R. Manchana et al., 2016). The SSM (Spring-Spring
MVC-MyBatis) framework integration has gained prominence in e-commerce
systems for its efficiency in handling business logic, web requests, and database
interactions. Spring MVC simplifies request routing and view rendering, while
MyBatis offers fine-grained SQL control, bridging the gap between object-
oriented programming and relational databases. Prior studies highlight SSM’s
effectiveness in reducing boilerplate code and improving transaction
management, making it ideal for scalable e-commerce applications.
This project leverages Spring Boot an extension of the Spring Framework to
streamline server-side development, coupled with MyBatis for seamless MySQL
database integration. By adopting SSM, the system ensures maintainability,
modularity, and performance, aligning with industry best practices in e-
commerce architecture.
2.2. Case Study: Shopping Cart System Using Spring Boot (zip code)
2.2.1. Overview about case study
This study has fundamentally developed a Shopping Cart System using
Spring Boot with a RESTful API architecture. This system was selected as the
case study because it aligns with modern e-commerce application needs,
providing a scalable and efficient backend solution. As online shopping
continues to grow, building a robust shopping cart system is essential for
seamless user experiences, including product management, cart operations, and
order processing.
2.2.2. Dependencies and properties
a. pom.xml:
- spring-boot-starter-parent is a starter project that provides the default
configuration for spring-based applications. The dependency management feature
of the starter parent allows the common dependencies to omit the <version> tag
in the pom.xml file
- spring-boot-starter-data-jpa: Used for working with JPA (Java Persistence
API), helping interact with databases through ORM like Hibernate. Provides
annotations such as @Entity, @Table, @Repository, @Transactional
- spring-boot-starter-validation: Supports input validation through
annotations like @NotNull, @Size, @Email, @Valid,...
- spring-boot-starter-web: Used for developing RESTful APIs with Spring
Boot. Includes Spring MVC, Embedded Tomcat, Jackson for JSON processing.
- modelmapper-spring: Provides ModelMapper, helps automatically convert
between DTO and Entity.
- mysql-connector-j: This library provides JDBC driver for application to
communicate with MySQL database.
- lombok: Helps reduce boilerplate code by automatically generating getters,
setters, constructors, builders, toString. Provides annotations like @Data,
@Builder, @AllArgsConstructor
b. application.properties:
In a Spring Boot application, the application.properties file inside the
src/main/resources folder is used to define application-related properties. This
file contains various configurations required to run the application in different
environments, and each environment can have its own set of properties. Inside
this file, different types of properties were defined: application & server
configuration, database connection configuration (MySQL), hibernate & JPA
configuration, defining a prefix for all API endpoints.
2.2.3. Implementation of application
a. Packages and models
This application is built through some packages: controller, dto, enums,
respone, request, repository, model, exceptions, service, config. The controller is
designed to contain API endpoints for interacting with the system. It receives
requests from the client, validates input data, calls the service layer to process
business logic, and returns the corresponding response.
The request represents data sent from the client and is used in the
@RequestBody annotation within the controller, helping to separate input data
from the entity.
The response represents data returned to the client and contains a mapping
class for response data, including: private String message → Stores the response
message and private Object data → Stores the response data.
The system consists of entities: Cart, CartItem, Category, Image, Oder,
OderItem, Product, User. The Entity Relationship diagram (ER diagram) here.
b. Build API (for product class)
 @RestController: Turns this class into a RESTful controller,
automatically returning JSON instead of rendering an HTML interface.
 @RequestMapping("${api.prefix}/products"): Sets the prefix to
/api/v1/products (since api.prefix is defined as /api/v1 in application.properties).
 @RequiredArgsConstructor: Automatically generates a constructor with
final fields (allowing IProductService to be injected into the controller without
needing @Autowired).
(1) POST (create in CRUD)
 @PostMapping("/add"): Defines the POST /api/v1/products/add API,
allowing new products to be added to the database.
 @RequestBody AddProductRequest product: Converts JSON from the
request into an AddProductRequest (DTO).
 productService.addProduct(product): Handles the logic of converting the
request into a Product entity and saving it to the database.
 productService.convertToDto(theProduct): Converts the Product entity
into a ProductDto to return a cleaner JSON response (hiding unnecessary
information).
(2) GET (read in CRUD)
 @GetMapping("product/{productId}/product"): Defines the GET
/api/v1/products/product/{productId}/product API to retrieve a product by its ID.
 @PathVariable Long productId: Extracts the {productId} value from the
URL and maps it to the productId variable.
 productService.getProductById(productId): Searches for a product by ID;
returns a Product if found, otherwise throws a ResourceNotFoundException.
 productService.convertToDto(product);: Converts the Product entity into a
ProductDto (DTO) to return only the necessary information, hiding sensitive data
such as createdAt, updatedAt, or complex relationships.
(3) PUT (update in CRUD)
 PutMapping("/product/{productId}/update"): Defines a PUT API to
update a product with the path /api/v1/products/product/{productId}/update.
 RequestBody ProductUpdateRequest request: Receives update data from
the request body in the form of a ProductUpdateRequest (DTO).
 PathVariable Long productId: Extracts productId from the URL to find the
product that needs to be updated.
 productService.updateProduct(request, productId): Checks if the product
exists, updates its details, and saves it to the database.
 productService.convertToDto(theProduct) transforms the Product entity
into a ProductDto to hide sensitive information before sending the response to the
client.
(4) DELETE (delete in CRUD)
 DeleteMapping("/product/{productId}/delete"): Defines a DELETE API
to remove a product with the path /api/v1/products/product/{productId}/delete
 PathVariable Long productId: Extracts productId from the URL to find the
product to be deleted.
 productService.deleteProductById(productId): Checks if the product
exists and deletes it if found.
Each API returns an ApiResponse with a success or error message. On
success, it returns HTTP status 200 OK along with the productDto data. If a
ResourceNotFoundException occurs, it returns HTTP status 404 Not Found with
an error message. For other errors, it returns HTTP status 500 Internal Server
Error with a detailed error message.

2.3. Findings
2.3.1. Analysis and Interpretation of the Results
Postman is not an integral part of the Spring Boot application but serves as a
valuable external tool for testing and interacting with the application's RESTful
API. Developers use Postman to send HTTP requests to the application's API
endpoints, making it easier to validate the API's functionality (I. Jraset et al.,
2023).
a. In case API fail: API Endpoint Mismatch Error When Making a
Request
{
"timestamp": "2025-03-29T22:33:18.796+00:00",
"status": 404,
"error": "Not Found",
"path": "/api/v1/products/by-brand"
}
This error occurs when the API path sent by the client does not match the
definition in the controller. It is often caused by: incorrect characters (e.g.,
/products/by-brand instead of /product/by-brand), missing or extra prefixes
(e.g., /api/v1/product instead of /api/product), or inconsistencies between the API
documentation and the actual code. From this error, it is clear that when building
and testing APIs, it is crucial to define clear and consistent endpoints.
b. In case API pass
Several typical API tests have been performed and can be accessed at the
following link.
@PostMapping("/add")
The system successfully processed the request to add a new product, with an
automatically incremented ID (ID = 1), demonstrating that the database's auto-
increment mechanism works correctly. All important data fields (name, brand,
price, inventory, description) were saved correctly, ensuring data integrity. The
API returned a response in the expected structure, including a success message
and data containing product information, making it easy for the frontend to
process and display. Notably, the processing time was only 138 ms, indicating a
fast response time and meeting performance requirements in a production
environment. This result confirms that the API is stable, reliable, and ready for
production deployment.
@GetMapping("product/{productId}/product")
The system successfully processed the request to filter products by the brand
"LG" and accurately returned the product with ID: 3, name: "Refrigerator,"
correctly fulfilling the query logic. The API adheres to the correct response
format with a structure of message and data, making it easy for the client to
identify the result. The query parameter ?brand=lg works effectively, proving
that the brand filtering mechanism operates correctly. In terms of performance,
the system returned a status of 200 OK with a processing time of 312 ms-
although slightly slow, likely due to the large product image size or suboptimal
query performance.
@PutMapping("/product/{productId}/update")
The system successfully processed the request to upload images for the
product (productId = 3), with two images created (imageId: 5 and 6). Important
information such as the image name (imageName) and download URL
(downloadUrl) is valid and accurate. The API returned a response in the correct
format, including a success message and data containing the list of uploaded
images. Notably, the system provides an image download endpoint
(/api/v1/images/image/download/{imageId}) that works immediately after the
upload. In terms of performance, the processing time was only 35 ms,
demonstrating extremely fast processing, with a compact response size and a
status of 200 OK, confirming the process was entirely successful.
@DeleteMapping("/product/{productId}/delete")
The system successfully processed the request to delete an item with the
message "Remove Item Success," confirming that the operation was completed.
The API is designed in a standard RESTful manner by using the DELETE
method combined with clear path parameters. The response returns data: null,
which is appropriate since no data is needed after a delete operation. Notably, the
processing time was only 35 ms, demonstrating that the system is highly
optimized for this operation.
2.3.2. Recommendations for Future Studies
For future research on securing shopping cart systems, researchers should
explore advanced security measures by integrating Spring Security with OAuth2
and JWT authentication. These mechanisms provide robust token-based
authentication and Role-Based Access Control (RBAC) to protect sensitive
endpoints like payment processing. Future studies should also focus on
preventing vulnerabilities such as SQL injection, CSRF, and XSS through
enhanced input validation and secure coding practices. AI-driven anomaly
detection in API requests could be a promising approach for real-time threat
detection.
To ensure system reliability, future research should develop automated
testing frameworks integrated with CI/CD pipelines. Tools like Postman and
RestAssured can be used for AI-driven test case prioritization, especially for
high-risk endpoints like checkout and payments. Optimized GitHub Actions or
Jenkins pipelines with security scanning tools like OWASP ZAP and SonarQube
would improve deployment security. Addressing real-world implementation
challenges is essential to bridging the gap between research and practical
applications.
3. Conclusion
This research has synthesized key findings from implementing an online
shopping cart system using Spring Boot MVC and RESTful API, while
successfully addressing the two initial research questions. Through the case
study, the critical role of API testing with Postman has been clarified,
demonstrating its effectiveness in enhancing system error detection. The results
confirm that the CRUD APIs for products, shopping carts, and orders operate
stably with fast response times. For future research, the author recommends
implementing advanced techniques such as Spring Security with JWT integration
for enhanced security, CI/CD deployment to automate testing processes, as well
as expanding the system with online payment and product recommendation
features to achieve optimal performance.

REFERENCES
1. Manchana, R. (2016). Building Scalable Java Applications: An In-Depth
Exploration of Spring Framework and its ecosystem. ResearchGate, doi:
10.61463/ijset.vol.4.issue3.103
2. K. Guntupally, R. Devarakonda and K. Kehoe, "Spring Boot based REST
API to Improve Data Quality Report Generation for Big Scientific Data: ARM
Data Center Example," 2018 IEEE International Conference on Big Data (Big
Data), Seattle, WA, USA, 2018, pp. 5328-5329, doi:
10.1109/BigData.2018.8621924.
3. Writer, S. (2020, November 10). Why Spring Framework is Preferred
Choice for Java Enterprise Apps? Evon Technologies.
4. Wei, T. (2022). Spring Boot based online shopping web application.
ScholarWorks.
5. Ijraset. (2023). Efficient Backend Development with Spring Boot: A
Comprehensive Overview. IJRASET. ISSN: 2321-9653

You might also like