Skip to content
OVEX TECH
Education & E-Learning

Build a Spring Boot REST API for E-commerce

Build a Spring Boot REST API for E-commerce

How to Build a Spring Boot REST API for an E-commerce Platform

This tutorial will guide you through building a robust backend for an e-commerce application using Spring Boot. You will learn to create a clean, well-structured REST API, implement essential features like authentication and payment processing, and structure your codebase like a professional developer. By the end, you’ll have a production-ready e-commerce backend and the confidence to build complex Spring Boot applications.

Prerequisites

  • Solid understanding of Java, including object-oriented programming concepts (classes, interfaces).
  • Basic knowledge of relational databases (tables, keys, relationships, SQL queries).
  • Familiarity with Spring Boot fundamentals, including dependency injection, beans, Flyway migrations, entities, repositories, and custom queries (equivalent to completing Part 1 of the course).

1. Setting Up Your Development Environment

Before diving into coding, you need to set up your project. We’ll use Git repositories provided for the course.

  1. Clone the Starter Repository: This repository contains the foundational code from Part 1, cleaned up for this course. Open your terminal or command prompt and run:
git clone [repository_url]

Replace [repository_url] with the actual URL of the Spring API starter repository from GitHub.

  1. Open the Project in Your IDE: IntelliJ IDEA Ultimate is highly recommended due to its excellent Spring Boot support. Other IDEs can also be used.
  2. Configure Database Settings: Navigate to src/main/resources/application.yaml. Update the MySQL database settings (username and password) to match your local configuration. This course uses MySQL.
    • Ensure you have MySQL installed and running on your machine.
  3. Enable Lombok Annotations: When you first run the application, IntelliJ may prompt you to enable annotation processing for Lombok. Accept this prompt to ensure Lombok annotations work correctly.
  4. Verify Application Startup: Run the application. It should start on port 8080. You’ll see a white-label error page initially, as we haven’t built a homepage yet.
  5. Verify Database Tables: Connect to your MySQL database using your IDE’s database tools or a separate client. Ensure that Flyway has successfully created the database tables (e.g., address, category, product, profile, user) in the database named store_api (or your configured name).

2. Understanding Web Fundamentals and Spring MVC

To build web applications and APIs, it’s crucial to understand how the web works and how Spring MVC facilitates this.

2.1 How the Web Works

  • Client-Server Model: Your browser (client) sends requests to a server, which processes them and sends back responses.
  • HTTP Protocol: This is the set of rules for data transfer over the internet. Key components include:
    • Request: Contains a method (e.g., GET, POST), a URL (the resource address), headers (metadata), and an optional body (data being sent).
    • Response: Contains a status code (e.g., 200 OK, 404 Not Found), headers (metadata about the response), and a body (the content returned).
  • Web Page Rendering:
    • Server-Side Rendering (SSR): The server generates the full HTML page and sends it to the browser. This is traditional.
    • Client-Side Rendering (CSR): The server sends raw data (often in JSON format), and JavaScript in the browser dynamically generates the page. This is common in modern applications.
  • APIs (Application Programming Interfaces): These allow different applications to communicate. RESTful APIs follow a set of standard rules for this communication, often exchanging data in JSON format.

2.2 Introduction to Spring MVC

Spring MVC is a framework within Spring for building web applications. It follows the Model-View-Controller (MVC) design pattern:

  • Model: Handles data and business logic.
  • View: Represents the user interface (e.g., HTML page).
  • Controller: Acts as the intermediary, handling requests and orchestrating responses.

3. Creating a Simple Controller and View

Let’s create a basic controller to handle requests and serve an HTML page.

  1. Create a Controller Class:
    • In your IDE, navigate to src/main/java and create a new package named controllers.
    • Inside the controllers package, create a new Java class named HomeController.
    • Annotate the class with @Controller. This tells Spring that this class is a bean and should handle web requests.
  2. Define a Request Mapping:
    • Inside HomeController, create a public method, e.g., index(), that returns a String. This string will represent the name of the view to render.
    • Annotate this method with @RequestMapping("/"). The forward slash (/) indicates the root URL of your application.
    • The method should return the name of the view, e.g., "index".
  3. Create the Static View:
    • In the src/main/resources directory, create a new directory named static. This is where static resources like HTML, CSS, and JavaScript files are placed.
    • Inside the static directory, create a new HTML file named index.html.
    • Add basic HTML content to index.html, for example:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home Page</title>
</head>
<body>
    <h1>Hello World</h1>
</body>
</html>
  1. Restart and Test: Restart your Spring Boot application. Navigate to http://localhost:8080 in your browser. You should see the “Hello World” message.

4. Implementing Dynamic Content with Thymeleaf

To make web pages dynamic, we use template engines. Thymeleaf is a popular choice for Spring Boot applications.

  1. Add Thymeleaf Dependency:
    • Open your pom.xml file.
    • Add the Thymeleaf starter dependency:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

After adding the dependency, refresh your Maven project to download it.

  1. Create the Templates Directory:
    • In src/main/resources, create a new directory named templates. Spring Boot automatically looks for Thymeleaf templates in this directory.
    • Move your index.html file from the static directory into the templates directory.
  2. Configure Thymeleaf Namespace:
    • Open index.html.
    • In the <html> tag, add the Thymeleaf namespace attribute:
<html lang="en" xmlns:th="http://www.thymeleaf.org">
  • Add Dynamic Content:
    • In your HomeController, inject a Model object as a parameter to your index() method.
    • Use the model.addAttribute() method to pass data to the view. The first argument is the variable name (used in the template), and the second is the value.
  • 
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class HomeController {
    
        @RequestMapping("/")
        public String index(Model model) {
            model.addAttribute("name", "Mosh"); // Add a dynamic name
            return "index"; // Refers to index.html in templates directory
        }
    }
    
    1. Update the HTML Template:
      • Open templates/index.html.
      • Replace the static text in the <h1> tag with a Thymeleaf expression to display the dynamic name:
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Home Page</title>
    </head>
    <body>
        <h1>Hello, <span th:text="${name}"></span>!</h1>
    </body>
    </html>

    th:text="${name}" tells Thymeleaf to replace the content of the <span> tag with the value of the name attribute passed from the controller.

    1. Restart and Test: Restart your application. Refresh http://localhost:8080. You should now see “Hello, Mosh!”.

    5. Building RESTful APIs with @RestController

    Instead of returning HTML pages, we can create APIs that return data, typically in JSON format.

    1. Create a REST Controller:
      • In the controllers package, create a new Java class named MessageController.
      • Annotate this class with @RestController. This annotation combines @Controller and @ResponseBody, indicating that the return value of the methods should be directly written to the HTTP response body, usually as JSON.
    2. Define an API Endpoint:
      • Create a public method, e.g., sayHello().
      • Annotate it with @RequestMapping("/hello") to map it to the /hello endpoint.
      • The method can return various data types, including strings, numbers, or custom objects.
    3. Return Simple Data:
      • Initially, let the method return a simple string:
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class MessageController {
    
        @RequestMapping("/hello")
        public String sayHello() {
            return "Hello World";
        }
    }
    
    1. Restart and Test: Restart the application. Navigate to http://localhost:8080/hello. You should see the text “Hello World”. Inspecting the page source will show only the text, not HTML markup.
    2. Return JSON Objects:
      • To return structured data, create a simple Plain Old Java Object (POJO) to represent the data. Create a new class Message in the entities package with a String text field, a constructor, and a getter (using Lombok annotations like @Getter and @AllArgsConstructor is efficient).
      • Modify the MessageController to return an instance of this Message object. Spring Boot, with Jackson (usually included by default), will automatically convert this Java object into a JSON response.
    
    // Assuming Message class exists with a constructor and getter for 'text'
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class MessageController {
    
        @RequestMapping("/hello")
        public Message sayHello() {
            return new Message("Hello World"); // Create and return a Message object
        }
    }
    

    Tip: If your JSON output is not formatted nicely in the browser, install a browser extension like “JSON Formatter” for Chrome or similar for other browsers.

    1. Restart and Test: Restart the application. Access http://localhost:8080/hello again. You will now see a JSON object like {"text": "Hello World"}.

    Tips for Maximizing Your Learning

    • Code Along: This is a hands-on course. Actively write the code as you follow the lessons.
    • Pace Yourself: If the videos feel too fast, watch a lesson once, take notes, and then re-watch and code at your own pace.
    • Engage with Exercises: The exercises and capstone projects are crucial for solidifying your understanding and building confidence. Don’t skip them.
    • Don’t Rush: Take your time to practice and ensure you understand each concept before moving on.

    What’s Next

    You’ve successfully set up your environment, understood basic web concepts, and learned to create both traditional web pages with Thymeleaf and modern RESTful APIs using Spring Boot. The next sections will delve deeper into building REST APIs, handling various HTTP requests, validating user input, implementing features like shopping carts, authentication, payment processing, and finally, deploying your application to the cloud.


    Source: Spring Boot Project: Build a REST API for an E-commerce Platform (YouTube)

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Written by

    John Digweed

    1,218 articles

    Life-long learner.