Building REST APIs with Spring Web
11 min read
Building REST APIs with Spring Web 🏗️
Welcome, aspiring coders, to this guide on building REST APIs with Spring Web! Ever wondered how different applications talk to each other, sharing information seamlessly? That's the magic of REST APIs, and today, we're going to unravel this magic using one of the most popular Java frameworks, Spring.
Think of yourself as a librarian. People come to you with requests for specific books. You, the librarian, need a system to understand these requests, find the right book, and hand it over. If the book is not available, you need to inform them about it. Building a REST API is quite similar. You're creating a system that listens for requests for information, processes them, and sends back a response.
By the end of this guide, you'll be equipped to build robust and efficient REST APIs that can power modern applications. So grab your favorite beverage ☕, and let's get started!
1. Introduction to Spring MVC and RESTful Architecture Concepts 🧐
The Problem: Imagine you're building a massive online store. You have a component that handles user accounts, another for product listings, and a third for processing orders. How do you make these different parts communicate with each other efficiently and in a standardized way? If every component has its own quirky way of talking, it would be like trying to have a conversation where everyone is speaking a different language—chaotic and unproductive!
The Solution: RESTful Architecture
REST (Representational State Transfer) is not a technology or a language, but a set of rules or architectural principles for designing networked applications. It provides a standardized way for systems to communicate over the internet.
Key Concepts of REST:
- Resources: In REST, everything is a "resource." A resource could be a user, a product, an order, or any other piece of information. Each resource is identified by a unique URI (Uniform Resource Identifier), like
/users/123or/products/45. - HTTP Methods: Clients interact with resources using standard HTTP methods. The most common ones are:
GET: To retrieve a resource. (e.g., get details of user 123)POST: To create a new resource. (e.g., create a new user)PUT: To update an existing resource completely. (e.g., update all details of user 123)DELETE: To remove a resource. (e.g., delete user 123)
- Statelessness: This is a core principle. Each request from a client to the server must contain all the information needed to understand and complete the request. The server does not store any information about the client's state between requests. Think of it like a vending machine: you put in your money and make a selection for each transaction, the machine doesn't remember your previous purchase. This makes the system more reliable and easier to scale.
Introducing Spring MVC
Spring MVC (Model-View-Controller) is a module within the Spring Framework that helps us build web applications following the MVC design pattern. In the context of REST APIs, we primarily focus on the Controller part to handle incoming requests and return data.
Imagine a busy restaurant. The DispatcherServlet in Spring MVC is like the host at the front door. It's the first point of contact for all incoming customer (HTTP) requests. The host doesn't cook the food but knows exactly which chef (Controller) is responsible for which type of dish (request).
Here’s a simplified flow:
- A client sends an HTTP request to your application.
- The
DispatcherServletintercepts this request. - It then consults the
HandlerMapping(a sort of menu) to figure out which@Controllermethod is responsible for handling this specific request URL. - Once the appropriate controller method is found, the
DispatcherServletsends the request to it. - The controller method processes the request, performs some business logic (perhaps by talking to a
Servicelayer), and returns some data. - This data is then converted into a format the client can understand (like JSON) and sent back as the HTTP response.
This organized flow keeps our code clean, separated, and much easier to manage, especially as our application grows.
2. Routing and Handling HTTP Requests: @RestController and @RequestMapping 🛣️
The Problem: Now that we understand the basic concepts, how do we actually tell our Spring application which method should handle a request to, say, /api/users? We need a way to map incoming URLs to specific pieces of our code.
The Solution: @RestController and @RequestMapping
These annotations are our signposts. They guide incoming requests to the correct destination within our code.
@RestController: This is a specialized version of the@Controllerannotation. When you put this on a class, you're telling Spring that this class is responsible for handling HTTP requests and that the return value of its methods should be written directly to the HTTP response body (typically as JSON), without looking for a view to render. This is exactly what we want for a REST API.@RequestMapping: This annotation is used to map web requests to specific handler classes and/or handler methods. You can use it at the class level to specify a base path for all methods in that class, and at the method level to specify the path for that particular method.
Let's see it in action:
package com.example.api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/greetings")
public class GreetingController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
@GetMapping("/goodbye")
public String sayGoodbye() {
return "Goodbye, World!";
}
}Breakdown of the code:
@RestController: We've marked ourGreetingControllerclass with this, so Spring knows it's a REST controller.@RequestMapping("/api/greetings"): This is placed at the class level. It means that any request to a URL starting with/api/greetingswill be handled by this controller.@GetMapping("/hello"): This is a more specific version of@RequestMapping(method = RequestMethod.GET). It tells Spring that thesayHello()method should handleGETrequests to/api/greetings/hello.@GetMapping("/goodbye"): Similarly, this mapsGETrequests for/api/greetings/goodbyeto thesayGoodbye()method.
Fun Fact: @GetMapping is a shortcut! Spring provides similar shortcuts for other HTTP methods like @PostMapping, @PutMapping, @DeleteMapping, and @PatchMapping. Using these makes your code more readable and concise.
So, if you run this application and send a GET request to http://localhost:8080/api/greetings/hello, you'll get a simple string "Hello, World!" back in the response.
3. Extracting Data: @PathVariable, @RequestParam, and @RequestBody 🎣
The Problem: Our API can now route requests, but what if the client wants to send us some information? For example, how do we get the ID of a specific user to fetch their details, or how do we get the new user's information when they want to create an account?
The Solution: Data Extraction Annotations
Spring provides a set of powerful annotations to extract data from incoming requests.
@PathVariable: This is used to extract values from the URL path itself. Imagine your URL is/users/123. The123is a variable part of the path that identifies a specific user.Example:
java@GetMapping("/users/{userId}") public String getUserById(@PathVariable Long userId) { return "Fetching details for user with ID: " + userId; }In this example, a
GETrequest to/users/123would result in theuserIdvariable being assigned the value123.@RequestParam: This is used to extract values from the query parameters of a URL. Query parameters are the key-value pairs that appear after the?in a URL. For instance, in/products?category=electronics,categoryis a request parameter.Example:
java@GetMapping("/products") public String getProductsByCategory(@RequestParam String category, @RequestParam(required = false) String brand) { if (brand != null) { return "Fetching " + category + " products of brand: " + brand; } return "Fetching all " + category + " products."; }A
GETrequest to/products?category=laptopswould call this method withcategoryset to "laptops". You can also make parameters optional by settingrequired = false.@RequestBody: This is used to extract the entire body of the incoming request. This is most commonly used withPOSTandPUTrequests where the client sends a JSON object containing the data for a new or updated resource.Example: Let's say we have a simple
Userclass:javapublic class User { private String username; private String email; // getters and setters }And our controller method:
java@PostMapping("/users") public String createUser(@RequestBody User newUser) { return "Created user: " + newUser.getUsername() + " with email: " + newUser.getEmail(); }To call this, a client would send a
POSTrequest to/userswith a JSON body like this:json{ "username": "john.doe", "email": "[email protected]" }Spring, with the help of the Jackson library (which is included by default in Spring Boot's web starter), will automatically deserialize this JSON into a
Userobject for you. Magic! ✨
4. Crafting Responses: Using ResponseEntity and Proper HTTP Status Codes 📜
The Problem: So far, we've been returning simple strings. But in a real-world API, you need more control. What if you want to tell the client that a resource was created successfully (201 Created) or that a resource they requested was not found (404 Not Found)? Simply returning a string doesn't convey this important status information.
The Solution: ResponseEntity
ResponseEntity is a powerful class in Spring that represents the entire HTTP response. It allows you to control everything: the response body, the HTTP status code, and the headers.
Using ResponseEntity is the standard industry practice because it gives you precise control over the response, which is crucial for building robust and predictable APIs.
Example:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/books")
public class BookController {
// A simple in-memory map to act as our database
private final Map<Long, String> books = new HashMap<>();
private long nextId = 1;
@PostMapping
public ResponseEntity<String> addBook(@RequestBody String bookTitle) {
books.put(nextId, bookTitle);
String responseBody = "Book added with ID: " + nextId;
nextId++;
return new ResponseEntity<>(responseBody, HttpStatus.CREATED);
}
@GetMapping("/{id}")
public ResponseEntity<String> getBook(@PathVariable Long id) {
if (books.containsKey(id)) {
return new ResponseEntity<>(books.get(id), HttpStatus.OK);
} else {
return new ResponseEntity<>("Book not found with ID: " + id, HttpStatus.NOT_FOUND);
}
}
}Breakdown of the code:
- In the
addBookmethod, after successfully adding a book, we return aResponseEntity. We include a success message in the body and set the HTTP status to201 Created. This is the standard way to indicate that a new resource has been successfully created. - In the
getBookmethod, we first check if the book exists.- If it does, we return the book title with an
HttpStatus.OK(which is status code 200), the standard response for successful HTTP requests. - If it doesn't exist, we return an error message with
HttpStatus.NOT_FOUND(status code 404). This clearly communicates to the client that the requested resource is not available.
- If it does, we return the book title with an
A funny exaggeration: Not using proper HTTP status codes is like having a conversation where you only ever say "yes," regardless of whether you understood the question, agreed with it, or have no idea what the other person is talking about. It leads to a lot of confusion!
5. Global Exception Handling: Cleaning Up Errors with @ControllerAdvice 🧹
The Problem: What happens if an unexpected error occurs in your controller? For example, what if a client provides invalid data that causes a NullPointerException? By default, Spring will show a generic and often ugly error page or response. This is not ideal for a professional API. We want to handle errors gracefully and return a consistent, structured error response to the client.
The Solution: @ControllerAdvice and @ExceptionHandler
A class annotated with @ControllerAdvice allows you to handle exceptions across the whole application in one global component. It can be viewed as an interceptor of exceptions thrown by methods annotated with @RequestMapping and the like.
@ExceptionHandler is an annotation used to handle specific exceptions and send the custom error response to the client.
Let's imagine a scenario: A client tries to fetch a book with an ID that is not in our collection. We want to create a custom exception for this.
// A custom exception
public class BookNotFoundException extends RuntimeException {
public BookNotFoundException(Long id) {
super("Could not find book with id: " + id);
}
}Now, let's create our global exception handler:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BookNotFoundException.class)
public ResponseEntity<String> handleBookNotFound(BookNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
// You can add more handlers for other exceptions
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGenericException(Exception ex) {
// Log the exception for debugging
return new ResponseEntity<>("An unexpected error occurred", HttpStatus.INTERNAL_SERVER_ERROR);
}
}And we would modify our BookController to throw this exception:
@GetMapping("/{id}")
public ResponseEntity<String> getBook(@PathVariable Long id) {
if (books.containsKey(id)) {
return new ResponseEntity<>(books.get(id), HttpStatus.OK);
} else {
throw new BookNotFoundException(id);
}
}How it works:
- When a
GETrequest is made to/api/books/{id}with an ID that doesn't exist, thegetBookmethod throws aBookNotFoundException. - The
@ControllerAdviceclass,GlobalExceptionHandler, catches this exception because it has a method annotated with@ExceptionHandler(BookNotFoundException.class). - The
handleBookNotFoundmethod is executed, and it returns a cleanResponseEntitywith the exception's message and a404 Not Foundstatus.
This approach keeps your controller code clean from error handling logic and allows you to define a consistent error response format for your entire API. It's like having a dedicated cleanup crew that takes care of any messes, so your chefs (controllers) can focus on preparing the dishes.
Further Reading and Resources 📚
- Spring Framework Documentation: https://docs.spring.io/spring-framework/docs/current/reference/html/web.html
- Building a RESTful Web Service with Spring Boot: https://spring.io/guides/gs/rest-service/
- Baeldung - Introduction to Spring MVC: https://www.baeldung.com/spring-mvc-tutorial
- Mozilla Developer Network (MDN) - HTTP response status codes: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
Challenge
You are tasked with building a RESTful API for managing a product inventory. Your goal is to implement a ProductController and a global exception handler to manage CRUD operations and errors gracefully.
Requirements:
Product Controller Setup:
- Annotate the
ProductControllerclass to function as a REST controller handling requests under the base path/api/products.
- Annotate the
Endpoint Implementation:
- Create Product (
POST /):- Accept a
Productobject from the request body. - Return a
ResponseEntitywith the HTTP status201 Created. - Include a
Locationheader in the response pointing to the URL of the newly created product (e.g.,/api/products/{id}).
- Accept a
- Retrieve Product by ID (
GET /{id}):- Accept a product
idas a path variable. - If the product is found, return it with an HTTP status
200 OK. - If the product is not found, throw a
ProductNotFoundException.
- Accept a product
- Update Product (
PUT /{id}):- Accept a product
idas a path variable and the updatedProductobject from the request body. - If the product is found, update it and return the updated product with an HTTP status
200 OK. - If the product is not found, throw a
ProductNotFoundException.
- Accept a product
- Delete Product (
DELETE /{id}):- Accept a product
idas a path variable. - Return a
ResponseEntitywith the HTTP status204 No Content.
- Accept a product
- Search Products (
GET /search):- Accept an optional
categoryrequest parameter. - Return a list of products filtered by the given category. If the
categoryparameter is not provided, return all products.
- Accept an optional
- Create Product (
Custom Exception:
- Create a custom unchecked exception class named
ProductNotFoundExceptionthat extendsRuntimeExceptionand has a constructor that accepts aStringmessage.
- Create a custom unchecked exception class named
Global Exception Handling:
- Implement a class annotated with
@ControllerAdvice. - Within this class, create a method using
@ExceptionHandlerto specifically handleProductNotFoundException. - This handler method should return a
ResponseEntitycontaining the exception's message and the HTTP status404 Not Found.
- Implement a class annotated with
Expected result
Your final code should consist of three completed components:
A
ProductNotFoundExceptionclass that extendsRuntimeException.A
ProductControllerclass annotated with@RestControllerand@RequestMapping("/api/products"). It must contain the following methods:- A
createProductmethod mapped toPOST /using@PostMapping, which accepts a@RequestBody Productand returns aResponseEntitywith status201 Createdand aLocationheader. - A
getProductByIdmethod mapped toGET /{id}using@GetMapping, which accepts a@PathVariable Long id, returns aProduct, and throwsProductNotFoundExceptionif the product is not found. - An
updateProductmethod mapped toPUT /{id}using@PutMapping, which accepts a@PathVariable Long idand a@RequestBody Product, returns the updatedProduct, and throwsProductNotFoundExceptionif the product is not found. - A
deleteProductmethod mapped toDELETE /{id}using@DeleteMapping, which accepts a@PathVariable Long idand returns aResponseEntity<Void>with status204 No Content. - A
searchProductsmethod mapped toGET /searchusing@GetMapping, which accepts an optional@RequestParam String categoryand returns aList<Product>.
- A
A
RestApiExceptionHandlerclass annotated with@ControllerAdvice. It must contain:- A method annotated with
@ExceptionHandler(ProductNotFoundException.class)that accepts the exception as an argument and returns aResponseEntity<String>with the error message andHttpStatus.NOT_FOUND.
- A method annotated with