Learn Spring · 4/15

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/123 or /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:

  1. A client sends an HTTP request to your application.
  2. The DispatcherServlet intercepts this request.
  3. It then consults the HandlerMapping (a sort of menu) to figure out which @Controller method is responsible for handling this specific request URL.
  4. Once the appropriate controller method is found, the DispatcherServlet sends the request to it.
  5. The controller method processes the request, performs some business logic (perhaps by talking to a Service layer), and returns some data.
  6. 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 @Controller annotation. 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:

java
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:

  1. @RestController: We've marked our GreetingController class with this, so Spring knows it's a REST controller.
  2. @RequestMapping("/api/greetings"): This is placed at the class level. It means that any request to a URL starting with /api/greetings will be handled by this controller.
  3. @GetMapping("/hello"): This is a more specific version of @RequestMapping(method = RequestMethod.GET). It tells Spring that the sayHello() method should handle GET requests to /api/greetings/hello.
  4. @GetMapping("/goodbye"): Similarly, this maps GET requests for /api/greetings/goodbye to the sayGoodbye() 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. The 123 is 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 GET request to /users/123 would result in the userId variable being assigned the value 123.

  • @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, category is 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 GET request to /products?category=laptops would call this method with category set to "laptops". You can also make parameters optional by setting required = false.

  • @RequestBody: This is used to extract the entire body of the incoming request. This is most commonly used with POST and PUT requests where the client sends a JSON object containing the data for a new or updated resource.

    Example: Let's say we have a simple User class:

    java
    public 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 POST request to /users with 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 User object 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:

java
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:

  1. In the addBook method, after successfully adding a book, we return a ResponseEntity. We include a success message in the body and set the HTTP status to 201 Created. This is the standard way to indicate that a new resource has been successfully created.
  2. In the getBook method, 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.

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.

java
// 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:

java
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:

java
@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:

  1. When a GET request is made to /api/books/{id} with an ID that doesn't exist, the getBook method throws a BookNotFoundException.
  2. The @ControllerAdvice class, GlobalExceptionHandler, catches this exception because it has a method annotated with @ExceptionHandler(BookNotFoundException.class).
  3. The handleBookNotFound method is executed, and it returns a clean ResponseEntity with the exception's message and a 404 Not Found status.

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 📚

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:

  1. Product Controller Setup:

    • Annotate the ProductController class to function as a REST controller handling requests under the base path /api/products.
  2. Endpoint Implementation:

    • Create Product (POST /):
      • Accept a Product object from the request body.
      • Return a ResponseEntity with the HTTP status 201 Created.
      • Include a Location header in the response pointing to the URL of the newly created product (e.g., /api/products/{id}).
    • Retrieve Product by ID (GET /{id}):
      • Accept a product id as 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.
    • Update Product (PUT /{id}):
      • Accept a product id as a path variable and the updated Product object 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.
    • Delete Product (DELETE /{id}):
      • Accept a product id as a path variable.
      • Return a ResponseEntity with the HTTP status 204 No Content.
    • Search Products (GET /search):
      • Accept an optional category request parameter.
      • Return a list of products filtered by the given category. If the category parameter is not provided, return all products.
  3. Custom Exception:

    • Create a custom unchecked exception class named ProductNotFoundException that extends RuntimeException and has a constructor that accepts a String message.
  4. Global Exception Handling:

    • Implement a class annotated with @ControllerAdvice.
    • Within this class, create a method using @ExceptionHandler to specifically handle ProductNotFoundException.
    • This handler method should return a ResponseEntity containing the exception's message and the HTTP status 404 Not Found.

Expected result

Your final code should consist of three completed components:

  1. A ProductNotFoundException class that extends RuntimeException.

  2. A ProductController class annotated with @RestController and @RequestMapping("/api/products"). It must contain the following methods:

    • A createProduct method mapped to POST / using @PostMapping, which accepts a @RequestBody Product and returns a ResponseEntity with status 201 Created and a Location header.
    • A getProductById method mapped to GET /{id} using @GetMapping, which accepts a @PathVariable Long id, returns a Product, and throws ProductNotFoundException if the product is not found.
    • An updateProduct method mapped to PUT /{id} using @PutMapping, which accepts a @PathVariable Long id and a @RequestBody Product, returns the updated Product, and throws ProductNotFoundException if the product is not found.
    • A deleteProduct method mapped to DELETE /{id} using @DeleteMapping, which accepts a @PathVariable Long id and returns a ResponseEntity<Void> with status 204 No Content.
    • A searchProducts method mapped to GET /search using @GetMapping, which accepts an optional @RequestParam String category and returns a List<Product>.
  3. A RestApiExceptionHandler class annotated with @ControllerAdvice. It must contain:

    • A method annotated with @ExceptionHandler(ProductNotFoundException.class) that accepts the exception as an argument and returns a ResponseEntity<String> with the error message and HttpStatus.NOT_FOUND.
java

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.