Building the Web Layer: Your First REST API

8 min read

Welcome to the web layer. If an application were a restaurant, the web layer would be the front-of-house staff: taking orders, making sure the requests are formatted correctly, passing them to the kitchen (the business logic), and bringing the final dish (the response) back to the customer.

In modern Spring Boot development, building the web layer almost always means building a RESTful API. Let us break down how to handle web requests, route them to the right Java methods, extract data from them, and send professional, secure responses back.


1. Introduction to REST: Resource-Based Thinking

Definition

REST (Representational State Transfer) is an architectural style for designing distributed systems. It relies on a stateless, client-server communication protocol, almost exclusively HTTP. In REST, data and functionality are considered "resources," which are accessed using standard Uniform Resource Identifiers (URIs).

The Problem

Before REST became the industry standard, web services were chaotic. Developers used protocols like SOAP or custom XML structures over HTTP. A URL to get a user might look like /executeUserRetrievalNow, and deleting a user might involve sending a POST request to /deleteUserProcess.

This meant that every time you integrated with a new API, you had to read a massive manual just to figure out what verbs the original developer decided to invent. It was the software equivalent of every city in the world using a different color for "Stop" on traffic lights.

The Solution: Resource-Based Thinking

REST solves this by forcing us to think in Resources (Nouns) rather than Actions (Verbs).

The actions are already provided by the HTTP protocol standard methods:

  • GET (Retrieve)
  • POST (Create)
  • PUT / PATCH (Update)
  • DELETE (Remove)

Real-World System Simulation: The Library

Imagine you are building a Library Management System.
Instead of creating chaotic URLs, you define the resource: books.

  • To get a list of books: You make a GET request to /books.
  • To add a new book: You make a POST request to /books.
  • To get a specific book: You make a GET request to /books/123.
  • To delete a specific book: You make a DELETE request to /books/123.

Notice how the URL (/books) barely changes? The HTTP method tells the server what action to perform. This is the core of industry-standard REST API design.


2. Controllers and Routing: @RestController and @RequestMapping

Definition

A Controller is a Java class responsible for listening to incoming HTTP requests, executing the necessary logic, and returning an HTTP response. Routing is the mechanism of mapping a specific URL path and HTTP method to a specific Java method inside that controller.

The Problem

When a user navigates to https://api.yourlibrary.com/books, that request hits your server. But your server might have 500 different Java classes. How does Spring Boot know exactly which method in which file should be executed for that specific URL? Without a routing mechanism, you would have to write a single, terrifying 10,000-line if/else statement to check the URL of every incoming request.

The Solution

Spring Boot solves this elegantly using annotations. We use @RestController to mark a class as a web controller, and @RequestMapping (along with its shortcuts) to define the routes.

Under the Hood

When your Spring Boot application starts, a component called the DispatcherServlet scans your code for classes annotated with @RestController. It builds an internal map (like a directory) linking URLs to specific Java methods. When a request comes in, the DispatcherServlet acts as a receptionist, checks the map, and forwards the request to the exact method instantly.

Industry Standard Implementation

java
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@RestController // 1. Tells Spring this class handles web requests and returns data (JSON)
@RequestMapping("/api/books") // 2. Sets the base URL for all methods in this class
public class BookController {

    // 3. Maps GET requests to /api/books to this method
    @GetMapping 
    public String getAllBooks() {
        return "Here are all the books!";
    }

    // 4. Maps POST requests to /api/books to this method
    @PostMapping
    public String createBook() {
        return "Book created successfully!";
    }
}

Note: In the past, developers used @Controller combined with @ResponseBody. Today, @RestController is the industry standard as it combines both, automatically converting your Java objects into JSON responses.


3. Handling Requests: Path Variables, Query Params, and Request Bodies

Definition

Request handling is the process of extracting dynamic data sent by the client. This data can be embedded in the URL path, attached as URL parameters, or included in the body of the HTTP request.

The Problem

Routing gets the request to the right method, but a method like getAllBooks() is static. What if the client wants to search for a book by a specific author? What if they want to look up book ID 42? What if they want to save a new book to the database and need to send the title, author, and page count? We need a way to grab this data from the HTTP request and put it into Java variables.

The Solution

Spring Boot provides three main annotations to extract data, and in the industry, you must know exactly when to use each.

1. @PathVariable (For Identifiers)

Use this when a value is part of the URI path. It is strictly used to identify a specific resource.

java
import org.springframework.web.bind.annotation.PathVariable;

// The {id} in the URL maps directly to the Long id parameter
@GetMapping("/{id}")
public String getBookById(@PathVariable Long id) {
    return "Fetching book with ID: " + id;
}

Client calls: GET /api/books/42

2. @RequestParam (For Filtering, Sorting, and Pagination)

Use this for optional data added to the end of a URL after a question mark ?.

java
import org.springframework.web.bind.annotation.RequestParam;

// Maps query parameters to method arguments
@GetMapping("/search")
public String searchBooks(
        @RequestParam String author, 
        @RequestParam(defaultValue = "10") int limit) {
    return "Fetching " + limit + " books by " + author;
}

Client calls: GET /api/books/search?author=Tolkien&limit=5

3. @RequestBody (For Complex Data/Payloads)

Use this when the client is sending a JSON object (usually in a POST or PUT request). Spring automatically deserializes (converts) the incoming JSON into a Java object.

java
import org.springframework.web.bind.annotation.RequestBody;

@PostMapping
public String createBook(@RequestBody Book newBook) {
    return "Saving new book: " + newBook.getTitle();
}

Client sends:

json
{
  "title": "The Hobbit",
  "author": "J.R.R. Tolkien"
}

4. Structuring Responses: DTOs and ResponseEntity

Definition

A DTO (Data Transfer Object) is an object used strictly to encapsulate data and transport it between the client and the server.
ResponseEntity is a Spring class that represents the entire HTTP response, allowing you to control the HTTP status code, headers, and the response body.

The Problem

Beginners often make two massive mistakes when building REST APIs:

  1. Returning Database Entities directly: Imagine you have a User entity connected to your database. It contains id, username, email, and passwordHash. If you return this entity directly from your controller, Spring converts the whole thing to JSON. Congratulations, you just leaked password hashes to the internet!
  2. Ignoring HTTP Status Codes: If a client requests a book that doesn't exist, and your server returns null but with a 200 OK HTTP status, the client app assumes the request was successful but the data is just weird. This causes applications to crash.

The Solution

Step 1: Use DTOs

Never return your database entities. Create specific DTOs for the exact data the client needs. In modern Java (Java 14+), we use record classes for DTOs because they are concise and immutable.

java
// Modern Java Record DTO
public record BookResponseDTO(Long id, String title, String author) {}

Step 2: Use ResponseEntity

Wrap your DTOs in a ResponseEntity to explicitly declare the HTTP status code.

  • Found a resource? Return 200 OK.
  • Created a resource? Return 201 Created.
  • Resource missing? Return 404 Not Found.

Industry Standard Example

java
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/books")
public class BookController {

    @GetMapping("/{id}")
    public ResponseEntity<BookResponseDTO> getBook(@PathVariable Long id) {
        // Simulated database lookup
        if (id == 99) {
            // 404 Not Found
            return ResponseEntity.notFound().build(); 
        }
        
        // Map database data to DTO (protecting sensitive info)
        BookResponseDTO response = new BookResponseDTO(id, "1984", "George Orwell");
        
        // 200 OK with the JSON body
        return ResponseEntity.ok(response); 
    }

    @PostMapping
    public ResponseEntity<BookResponseDTO> createBook(@RequestBody BookRequestDTO requestDTO) {
        // ... logic to save book to database ...
        
        BookResponseDTO response = new BookResponseDTO(1L, requestDTO.title(), requestDTO.author());
        
        // 201 Created (Best practice for POST requests)
        return ResponseEntity.status(HttpStatus.CREATED).body(response);
    }
}

By combining @RestController, strict DTOs, and ResponseEntity, you have built a web layer that is secure, predictable, and professional. You are no longer just making Java methods; you are crafting a standardized API that any frontend developer or mobile app can easily consume.


References & Extra Reading

Challenge

You are tasked with building the web layer for a product management system. Your goal is to create a complete Spring Boot REST controller named ProductController.

This controller will manage product resources and must expose a set of secure and well-structured API endpoints. You will be provided with the necessary Data Transfer Objects (DTOs) and a mock ProductService class to handle business logic.

Requirements:

  1. Define a class named ProductController.

  2. Mark the class as a Spring REST controller that handles requests under the base path /api/products.

  3. Implement the following five endpoints:

    • Create a Product:

      • HTTP Method & Path: POST /api/products
      • Request Body: Accepts a ProductRequestDto object.
      • Response: Returns the newly created ProductResponseDto inside a ResponseEntity with an HTTP status of 201 Created.
    • Get a Single Product by ID:

      • HTTP Method & Path: GET /api/products/{id}
      • Path Variable: An Integer named id.
      • Response: Returns the corresponding ProductResponseDto in a ResponseEntity with an HTTP status of 200 OK. If the product is not found, it should return a 404 Not Found status.
    • Get All Products with Optional Filtering:

      • HTTP Method & Path: GET /api/products
      • Query Parameter: An optional String parameter named category. If provided, the service will filter by this category.
      • Response: Returns a List<ProductResponseDto> in a ResponseEntity with an HTTP status of 200 OK.
    • Update a Product:

      • HTTP Method & Path: PUT /api/products/{id}
      • Path Variable: An Integer named id.
      • Request Body: Accepts a ProductRequestDto object containing the updated data.
      • Response: Returns the updated ProductResponseDto in a ResponseEntity with an HTTP status of 200 OK. If the product to update is not found, it should return a 404 Not Found status.
    • Delete a Product:

      • HTTP Method & Path: DELETE /api/products/{id}
      • Path Variable: An Integer named id.
      • Response: Returns an empty ResponseEntity with an HTTP status of 204 No Content on success. If the product to delete is not found, it should return 404 Not Found.

Expected result

Your solution should be a single Java class named ProductController. This class must be fully annotated to function as a Spring REST controller, handling all the requirements specified in the instructions.

java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    private final ProductService productService = new ProductService();

    @PostMapping
    public ResponseEntity<ProductResponseDto> createProduct(@RequestBody ProductRequestDto productRequest) {
        ProductResponseDto createdProduct = productService.createProduct(productRequest);
        return new ResponseEntity<>(createdProduct, HttpStatus.CREATED);
    }

    @GetMapping("/{id}")
    public ResponseEntity<ProductResponseDto> getProductById(@PathVariable Integer id) {
        return productService.findProductById(id)
                .map(product -> new ResponseEntity<>(product, HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    @GetMapping
    public ResponseEntity<List<ProductResponseDto>> getAllProducts(@RequestParam(required = false) String category) {
        List<ProductResponseDto> products = productService.findAllProducts(category);
        return new ResponseEntity<>(products, HttpStatus.OK);
    }

    @PutMapping("/{id}")
    public ResponseEntity<ProductResponseDto> updateProduct(@PathVariable Integer id, @RequestBody ProductRequestDto productRequest) {
        return productService.updateProduct(id, productRequest)
                .map(updatedProduct -> new ResponseEntity<>(updatedProduct, HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(@PathVariable Integer id) {
        boolean isDeleted = productService.deleteProduct(id);
        if (isDeleted) {
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
}

Key validation points:

  • Class Annotations: The class must have @RestController and @RequestMapping("/api/products").
  • Method Annotations: Each method must have the correct HTTP mapping annotation (@PostMapping, @GetMapping, @PutMapping, @DeleteMapping) and path, including path variables like /{id}.
  • Parameter Annotations: Parameters must be correctly annotated with @RequestBody, @PathVariable, and @RequestParam. The required = false attribute is crucial for the optional category parameter.
  • Return Type: All methods must return ResponseEntity parameterized with the correct type (ProductResponseDto, List<ProductResponseDto>, or Void).
  • Response Logic: The code must construct ResponseEntity objects with both the data body (where applicable) and the correct HttpStatus code (CREATED, OK, NO_CONTENT, NOT_FOUND) based on the outcome of the service call.
java

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.