Skip to main content

REST API Development in Spring Boot

Modern applications rarely operate in isolation. Mobile apps, web frontends, and microservices constantly exchange data. This communication happens almost entirely through APIs, specifically using the REST (Representational State Transfer) architectural style.

Spring Boot makes building REST APIs incredibly elegant by utilizing highly specialized annotations. In this guide, we will break down the entire request lifecycle, internal mechanisms, and build a complete Employee Management API.


1. What is a REST API?

Standard Definition

A REST API is a web service that follows REST principles, allowing systems to communicate over standard HTTP protocols using structured data (usually JSON or XML).

It maps standard HTTP Verbs to CRUD operations:

  • GET /employees: Retrieves employee data (Read).
  • POST /employees: Creates a new employee (Create).
  • PUT /employees/101: Updates an employee's data (Update).
  • DELETE /employees/101: Deletes the employee (Delete).

The REST Architecture Request Flow

Client (Mobile / React / Angular) | HTTP Request (JSON) | V [ DispatcherServlet ] | V [ Controller Layer ] | V [ Service Layer ] | V [ Repository Layer ] -> Database | JSON Response | Client

2. The Controller Layer & @RestController

A Controller is the Spring component physically responsible for receiving the incoming HTTP request, routing it to business logic, and sending the response back to the client.

@RestController public class EmployeeController { @GetMapping("/hello") public String hello() { return "Welcome to Learn Here Fun"; } }

Internal Working of @RestController

@RestController is fundamentally different from the standard @Controller used in Spring MVC.

Internally, it is a meta-annotation composed of two parts: @Controller + @ResponseBody.

  • @Controller registers the class in the IOC container so the DispatcherServlet can route requests to it.
  • @ResponseBody instructs Spring to bypass standard view resolution (like trying to find a JSP or Thymeleaf HTML page). Instead, it automatically passes the returned Java object to a HttpMessageConverter (specifically Jackson), serializes it into a JSON string, and writes it directly to the HTTP response body.

3. URL Routing: @RequestMapping

@RequestMapping defines the base URL namespace for an entire controller.

@RestController @RequestMapping("/employees") public class EmployeeController { @GetMapping public String getEmployees() { return "All Employees"; } }

Because of the class-level annotation, the method above is now accessible specifically at GET /employees.


4. The Employee Data Model

Before implementing our HTTP methods, we need a standard Java POJO to represent our data.

public class Employee { private Long id; private String name; private String department; private Double salary; // Constructors, Getters, and Setters omitted for brevity }

5. Fetching Data: @GetMapping & Parameters

Retrieving All Resources

@GetMapping public List<Employee> getAllEmployees() { return List.of( new Employee(1L, "Madhu", "IT", 50000.0), new Employee(2L, "Rahul", "HR", 45000.0) ); }

@PathVariable (URL Segments)

Used to extract dynamic values directly from the URL path. Essential for fetching a single specific resource.

@GetMapping("/{id}") public Employee getEmployeeById(@PathVariable Long id) { return new Employee(id, "Madhu", "IT", 50000.0); }

Request: GET /employees/101 → The 101 is automatically bound to the id variable.

@RequestParam (Query Parameters)

Used to extract optional data appended after the ? in a URL, usually for searching or filtering.

@GetMapping("/filter") public String filterEmployees( @RequestParam String department, @RequestParam Double salary) { return department + " - " + salary; }

Request: GET /employees/filter?department=IT&salary=50000


6. Mutating Data: POST, PUT, PATCH, DELETE

@PostMapping & @RequestBody

Used to create brand new resources. The @RequestBody annotation is mandatory. It instructs Spring's MappingJackson2HttpMessageConverter to read the incoming JSON payload and instantly deserialize it into your Java Employee object.

@PostMapping public Employee saveEmployee(@RequestBody Employee employee) { // Normally you would pass this to a Service/Repository to save to DB return employee; }

@PutMapping vs @PatchMapping

Annotation Purpose Requirement
@PutMapping Complete Update Client must send the entire object payload. The existing database row is completely overwritten.
@PatchMapping Partial Update Client sends only the specific fields that changed (e.g., just changing the salary).
@PutMapping("/{id}") public Employee updateEmployee( @PathVariable Long id, @RequestBody Employee employee) { employee.setId(id); // Ensure ID matches the path return employee; }

@DeleteMapping

Used specifically to remove a resource. Typically it returns a 204 No Content status or a simple confirmation string.

@DeleteMapping("/{id}") public String deleteEmployee(@PathVariable Long id) { return "Employee Deleted: " + id; }

7. Advanced Endpoints: HTTP Headers

Often APIs require authorization tokens or custom metadata. You extract these using @RequestHeader.

@GetMapping("/secure") public String getSecureData(@RequestHeader("Authorization") String token) { // Token format: "Bearer eyJhbGciOiJIUzI1NiIsInR..." return token; }

8. Interview Checklist

Top Technical Interview Questions

Q1: What is the exact difference between @Controller and @RestController?
A: @Controller is used in standard Spring MVC applications to return View names (like JSP or Thymeleaf pages) resolved by a ViewResolver. @RestController is a convenience annotation that combines @Controller and @ResponseBody, ensuring the returned Java object is instantly serialized into JSON/XML and written directly to the HTTP response.

Q2: How does @RequestBody work internally?
A: When a request arrives, the DispatcherServlet delegates it to a HandlerAdapter. Detecting @RequestBody, Spring triggers an HttpMessageConverter (specifically the MappingJackson2HttpMessageConverter). This uses Jackson's ObjectMapper to deserialize the incoming JSON payload into the target Java object via reflection.

Q3: What is the difference between @PathVariable and @RequestParam?
A: @PathVariable extracts values embedded directly within the URL path string (e.g., /employees/101), commonly used to identify a specific resource. @RequestParam extracts data from the query string appended after a ? (e.g., /employees?department=IT), commonly used for sorting, filtering, or pagination metadata.

Internal Architecture Classes to Memorize

To demonstrate a senior-level understanding of the REST request pipeline, be prepared to discuss these internal Spring framework components:

  • DispatcherServlet (The Front Controller)
  • HandlerMapping (Specifically RequestMappingHandlerMapping)
  • HandlerAdapter
  • HttpMessageConverter
  • ObjectMapper (The core Jackson serialization engine)
Thanks for reading Learn Here Fun Pedia! In this tutorial, we explore Spring Boot REST APIs from basic concepts to internal architecture, including annotations, request processing, and interview questions.

Comments

Popular posts from this blog

How I Got Selected in MNC

Virtusa Sometimes success does not come from having the best coding skills or the perfect roadmap. Sometimes it comes from simply refusing to quit. This is the honest story of how I transitioned from a confused, rejected fresher to getting selected as an Associate Engineer at Virtusa. The Beginning: Confused About My Future After completing my graduation, I stared blankly at my career options. Like many freshers, I lacked a clear direction. Should I join a Java course? Should I prepare on my own? Should I just wait for campus placement opportunities? One day, I called my friend Chetan. He suggested I join Naresh i Technologies and start learning Java seriously. Still unsure of my path, I told him I needed time to think about it. A couple of days later, my phone buzzed with a WhatsApp message offering a job opportunity. They asked me to come for the next round of the recruitment process. Excitement completely took over. I packed my bags, traveled to th...

Spring Boot Introduction

Spring Boot Introduction: Architecture, Dependencies, and Embedded Servers Modern enterprise applications demand rapid development, frictionless deployment, and absolute minimal configuration. Before Spring Boot arrived, developers utilizing the Spring Framework wasted immense amounts of time configuring XML files, managing clashing dependencies, setting up clunky application servers, and stitching various Spring modules together manually. To eliminate these bottlenecks, Pivotal introduced Spring Boot . Built entirely on top of the traditional Spring Framework, Spring Boot is an "opinionated" framework. It aggressively simplifies application development by injecting auto-configuration, packaging starter dependencies, and embedding web servers directly into your application. This allows backend developers to focus entirely on building business logic rather than wrestling with infrastructure setup. What is Spring Boot? Spring Boot is a powerful extens...

Strings in C

C Programming: Working with Strings Unlike modern programming languages like Python or Java, C does not possess a dedicated "String" data type. Instead, C treats a string as a simple 1D array of characters. Real-life example: Think of a freight train. The train does not exist as one solid object; it consists of individual boxcars linked together. Similarly, a C string links individual characters side-by-side in memory. To let the computer know the train has ended, C attaches a special "caboose" called the Null Terminator ( \0 ). 1. Essential String Functions Handling strings manually requires complex loops. To save time, C provides a built-in library called <string.h> that contains powerful functions to manipulate text. strlen(): You use this to find the exact length of a string. The compiler counts the characters until it hits the \0 terminator. It does not count the terminator itself. strcpy(): You ...