Module 3: Spring Boot Fundamentals - Your First REST API

With a solid Java foundation, it's time to unleash the power of Spring Boot. Let's build our first web service!

3.1 & 3.2 Creating and Understanding the Project Structure

As we did in Module 1, we start with a fresh project from start.spring.io. For this module, the only dependency we need is Spring Web. Once you generate, download, and open the project in your IDE, you'll see a standard directory layout. Understanding this structure is key to staying organized.

  • pom.xml: The "Project Object Model" file for Maven. It's the heart of your project's configuration, defining its name, dependencies (like Spring Web), and how to build it.
  • src/main/java: This is where 99% of your application's Java code will live.
    • Inside, you'll find your main application class, marked with the @SpringBootApplication annotation. This annotation is a magical combination of three others, and it's the entry point that kicks off your entire application.
  • src/main/resources: A folder for non-Java files.
    • application.properties: A crucial file for configuring your application (e.g., setting the server port, database connection details, etc.).
  • src/test/java: A parallel source folder where you'll write your automated tests.

3.3 Controllers, Services, and Repositories

Modern applications are built using a layered architecture to achieve Separation of Concerns. This is a fundamental design principle that makes code easier to develop, test, and maintain. Each layer has a distinct responsibility.

Client Request (Browser/Postman)

Controller Layer (Handles HTTP requests)

Service Layer (Executes business logic)

Repository Layer (Accesses data)

Database

The Controller Layer

Analogy: The Restaurant Host. The controller is the first point of contact for any incoming request. Its only job is to greet the request, understand what is being asked for (e.g., "I want to see the menu" or "I want to place an order"), and delegate the task to the appropriate service. It doesn't cook the food or wash the dishes; it just manages the flow of requests and responses.

The Service Layer

Analogy: The Chef. This is where the core work, or "business logic," happens. The chef takes the order from the host (Controller), gathers the ingredients (from the Repository), and performs the actual work of preparing the meal. The service layer orchestrates the logic, such as "to open a new bank account, we must first verify the customer's ID, then check for an initial deposit, then create the account record."

The Repository Layer

Analogy: The Pantry/Storage Room. The repository's sole responsibility is to manage data. It interacts directly with the database. The chef (Service) doesn't need to know where each ingredient is stored; they simply ask the pantry staff (Repository) for "two tomatoes" or to "store this new batch of flour." The repository handles the low-level details of fetching, saving, updating, and deleting data.

3.4 REST APIs – An Introduction

An API (Application Programming Interface) is a contract that allows two pieces of software to communicate. A REST API is a popular type of API that follows the principles of REST (REpresentational State Transfer), an architectural style that uses the standard HTTP protocol.

Think of it like ordering food at a restaurant:

  • Resource: The "thing" you are interested in. In our project, resources will be Customers, Accounts, and Transactions. At a restaurant, a resource is a dish on the menu.
  • URI (Uniform Resource Identifier): The unique address for a resource. Example: /api/accounts/12345. At a restaurant, it's the name of the dish, like "Classic Burger."
  • HTTP Verbs (Methods): The action you want to perform on the resource.
    • GET: To retrieve a resource (View the menu).
    • POST: To create a new resource (Place a new order).
    • PUT: To update an existing resource (Change your order).
    • DELETE: To remove a resource (Cancel your order).

3.5 Building and Testing Your First REST API with Postman

Let's put theory into practice! We will create our first Controller, which will expose a simple "Hello World" endpoint.

Step 1: Create the Controller

Inside your src/main/java package, create a new Java class called HelloWorldController.java.


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

// @RestController tells Spring that this class will handle web requests.
// It combines @Controller and @ResponseBody, which means the return value
// of methods will be written directly to the HTTP response body.
@RestController
public class HelloWorldController {

    // @GetMapping("/hello") maps HTTP GET requests for the "/hello" URL
    // to this method.
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, World! Welcome to your first Spring Boot API!";
    }
}

Step 2: Run the Application

Go to your main application class (the one with @SpringBootApplication) in your IDE. Right-click on it and select "Run". Your Spring Boot application will start, and you'll see a lot of log output in the console. Near the end, you should see a line indicating that Tomcat has started on a port (usually 8080).

Step 3: Test with Postman

Postman is an essential tool for any API developer. It allows you to send HTTP requests to your API and inspect the responses without needing to build a frontend. If you haven't already, download and install it.

  1. Open Postman and click the "+" to create a new request.
  2. Ensure the HTTP method is set to GET.
  3. In the URL bar, type: http://localhost:8080/hello
  4. Click the blue Send button.
Expected Result: In the response section at the bottom of the Postman window, you should see the text "Hello, World! Welcome to your first Spring Boot API!" with a status code of 200 OK.

Congratulations! You have successfully built and tested your first REST API endpoint. You've instructed Spring Boot to listen for GET requests at a specific URL and respond with a simple message. This is the fundamental building block for the entire banking application we are about to create.