back

Spring Boot - REST API

6 min read6 views1 reactions
Spring BootSpringbootREST APIRESTSpring frameworkMVC architectureAPIs

API - Application Programming Interface

Spring boot work in MVC Architechture

MVC = Model, View, Controller → its a design pattern via which we acheive separation of concern

Spring Boot applications work on the MVC (Model-View-Controller) architecture — a design pattern that helps achieve separation of concerns.

In this pattern:

By following MVC, Spring Boot makes it easier to build scalable, maintainable, and well-structured applications.

Spring MVC - a traditional flow


Flow Breakdown

  1. Request → DispatcherServlet

    • A request (say, from a browser or Postman) comes in.

    • It’s handled first by DispatcherServlet, which acts as the front controller in Spring MVC — the main entry point for all web requests.

  2. DispatcherServlet → HandlerMapping

    • The DispatcherServlet asks HandlerMapping to determine which controller should handle this request.

    • HandlerMapping checks the URL and identifies the correct controller method

  3. DispatcherServlet → HandlerAdapter

    • Once the correct controller is identified, the HandlerAdapter is used to invoke that controller method.
  4. HandlerAdapter → Controller

    • The Controller executes and calls the Service layer to perform business logic.

    • The Service may internally call the Repository layer, which interacts with the database (DB).

  5. Controller → Model & View Name

    • After completing the logic, the controller sets data into a Model (the part that holds response data).

    • It also returns a view name, which tells Spring which view (like JSP, Thymeleaf, etc.) to render.

  6. DispatcherServlet → ViewResolver

    • The ViewResolver takes the view name and maps it to an actual view file (e.g., home.html or result.jsp).
  7. DispatcherServlet → View

    • The DispatcherServlet sends the model data to the resolved view.
  8. Response → Client

    • The view (now populated with model data) is rendered as HTML and sent back to the client as the HTTP response.

Layers on the Right Side

NOTE:

This is the classic MVC flow used when building web apps with UI rendering (e.g., JSP, Thymeleaf) not REST APIs.

In REST APIs, the flow usually stops after the controller returns data (skipping ViewResolver and View).

How does web server works in spring boot


Step-by-Step Explanation

  1. Client → Tomcat (Web Server)

    • The client (browser, Postman, etc.) sends an HTTP request to your Spring Boot app.

    • Inside Spring Boot, an embedded Tomcat server runs automatically (no need for an external server).

    • Tomcat receives the HTTP request and maps it to the appropriate servlet.

  2. Tomcat → DispatcherServlet

    • Once Tomcat identifies that the request should be handled by Spring, it forwards it to the DispatcherServlet — the core front controller of Spring MVC.

    • The DispatcherServlet handles routing and dispatching:

      1. It creates HttpServletRequest and HttpServletResponse objects.

      2. It delegates the request to the appropriate HandlerMapping (e.g., a method annotated with @GetMapping, @PostMapping, etc.).

      3. It then invokes the corresponding controller method.

  3. DispatcherServlet → Controller

    • The Controller receives the request.

    • It performs several possible tasks:

      1. Validate input data

      2. Authenticate users (if needed)

      3. Execute business logic

      4. Perform database queries via the service/repository layer

  4. Controller → HttpMessageConverter

    • Once the controller method returns a Java object (like a DTO or POJO), Spring uses the HttpMessageConverter to serialize it.

    • For REST APIs, this converter (usually Jackson) converts the Java object into JSON format.

  5. HttpMessageConverter → Tomcat → Client

    • The serialized JSON is wrapped inside the HTTP response.

    • Tomcat sends the final JSON response back to the client.

3 Layer Architecture


Connecting to DB (Postgresql using NEON db)


Steps to follow

  1. Create a new database on Neon.tech.

    After creating, go to the “Connection Details” section — you’ll see a connection string like:

     postgresql://<username>:<password>@<host>/<database>?sslmode=require
    
  2. Copy those values and paste them into your application.properties like this:

     spring.datasource.url=jdbc:postgresql://<host>/<database>?sslmode=require
     spring.datasource.username=<username>
     spring.datasource.password=<password>
    
     spring.jpa.hibernate.ddl-auto=update
     spring.jpa.show-sql=true
     spring.jpa.properties.hibernate.format_sql=true
    

Imp stuff


HikariPool

When you see HikariPool in the logs after connecting to your PostgreSQL database, it refers to HikariCP, the default connection pool used by Spring Boot.

A Connection Pool is like a “ready-to-use collection of database connections” that your application can borrow from, instead of creating a brand-new connection every time it needs to talk to the database.

→ BUT WHY?

→ HOW IT WORKS

  1. At startup, the pool (like HikariCP) creates a small set of connections (say 10).

  2. When your code needs a DB connection, it borrows one from the pool.

  3. Once done (e.g., after a query), it returns the connection to the pool instead of closing it.

  4. The same connection can then be reused by another request.

Also, when returning data from any API controller, we usually don’t return raw DTOs or strings.

Instead, we return a ResponseEntity<?>, which allows us to define status codes, response bodies, and headers more cleanly.

Simple Spring Boot REST API Example


Let’s build a basic "User API" that returns a list of users.

1. Project Structure

spring-boot-rest-api/
 ├── src/
 │   ├── main/
 │   │   ├── java/com/example/demo/
 │   │   │   ├── DemoApplication.java
 │   │   │   ├── controller/UserController.java
 │   │   │   ├── model/User.java
 │   │   │   └── service/UserService.java
 │   │   └── resources/
 │   │       └── application.properties
 └── pom.xml

2. Main Application File

// DemoApplication.java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

3. Model Class

// User.java
package com.example.demo.model;

public class User {
    private int id;
    private String name;
    private String email;

    // Constructor
    public User(int id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }

    // Getters and setters
    public int getId() { return id; }
    public String getName() { return name; }
    public String getEmail() { return email; }
}

4. Service Layer

// UserService.java
package com.example.demo.service;

import com.example.demo.model.User;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserService {

    public List<User> getAllUsers() {
        return List.of(
                new User(1, "Mahendra", "mahendra@example.com"),
                new User(2, "John", "john@example.com")
        );
    }
}

5. Controller Layer

// UserController.java
package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
public class UserController {

    private final UserService userService;

    // Constructor Injection (best practice)
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/users")
    public List<User> getUsers() {
        return userService.getAllUsers();
    }
}

6. Run the App

Start the application using:

mvn spring-boot:run

Then open your browser or Postman and visit:
http://localhost:8080/users

You’ll get a JSON response like:

[
  {
    "id": 1,
    "name": "Mahendra",
    "email": "mahendra@example.com"
  },
  {
    "id": 2,
    "name": "John",
    "email": "john@example.com"
  }
]

What This Example Shows

And that’s it! You just built a simple REST API using Spring Boot, from project setup to returning JSON data through a controller. Now you can experiment with this, by create POST endpoints, handle exceptions, and make it more advanced step by step. Keep exploring, keep building.

Till then, Happy Learning.