back
Spring Boot - REST API
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:
Model represents the data and business logic,
View handles the UI or response representation, and
Controller manages the request flow between them.
By following MVC, Spring Boot makes it easier to build scalable, maintainable, and well-structured applications.
Spring MVC - a traditional flow

Flow Breakdown
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.
DispatcherServlet → HandlerMapping
The DispatcherServlet asks HandlerMapping to determine which controller should handle this request.
HandlerMapping checks the URL and identifies the correct controller method
DispatcherServlet → HandlerAdapter
- Once the correct controller is identified, the HandlerAdapter is used to invoke that controller method.
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).
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.
DispatcherServlet → ViewResolver
- The ViewResolver takes the view name and maps it to an actual view file (e.g., home.html or result.jsp).
DispatcherServlet → View
- The DispatcherServlet sends the model data to the resolved view.
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
Service (Business Logic):
Contains business operations, validation, and logic.
Repository (Data Access):
Handles direct interaction with the database (CRUD operations).
DB:
The actual database storing your data.
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
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.
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:
It creates
HttpServletRequestandHttpServletResponseobjects.It delegates the request to the appropriate HandlerMapping (e.g., a method annotated with
@GetMapping,@PostMapping, etc.).It then invokes the corresponding controller method.
DispatcherServlet → Controller
The Controller receives the request.
It performs several possible tasks:
Validate input data
Authenticate users (if needed)
Execute business logic
Perform database queries via the service/repository layer
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.
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
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=requireCopy those values and paste them into your
application.propertieslike 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?
Creating a database connection is slow (handshake, authentication, network round trips — all of which take time).
If every request created a new connection, your app would be very slow and consume lots of resources.
So instead, the app keeps a few connections open in memory and reuses them whenever needed.
→ HOW IT WORKS
At startup, the pool (like HikariCP) creates a small set of connections (say 10).
When your code needs a DB connection, it borrows one from the pool.
Once done (e.g., after a query), it returns the connection to the pool instead of closing it.
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
Spring Boot auto-configures Tomcat as an embedded web server.
Controller handles incoming requests (
/users).Service layer provides data.
The response is automatically converted to JSON by HttpMessageConverter.
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.