Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 15

Building REST Controllers: Spring Boot vs. Express.js

This lesson is built with resources from youtube.com, spring.io and 1 more site.

Hello! In our last session, we built your confidence in diagnosing and fixing common Spring Boot startup errors like PortInUseException and NoSuchBeanDefinitionException. You learned to read stack traces effectively, a crucial skill for any developer. With that foundation, our application is now stable and ready for us to build upon.

Today, we begin the exciting work of making our application do something useful. We're moving into the Building REST APIs with Spring MVC module. This lesson focuses on the very first step: creating endpoints that can receive and respond to web requests.

Our learning outcome is to create a REST controller with request mappings (@GetMapping, @PostMapping) that returns static data, comparing it to Express.js route handlers.

You have extensive experience creating routes in Express.js. As you'll see, the concepts are remarkably similar in Spring Boot, though the syntax and underlying mechanics are different. We will map every new Spring concept back to its equivalent in the MERN world you know so well.

1. The Controller: Your Application's Front Door

In a web application, something has to be the first point of contact for an incoming HTTP request. In Express.js, this is handled by the app object and the route handlers you define (e.g., app.get(...)).

In Spring MVC, this role is played by the DispatcherServlet and Controllers.

  • The DispatcherServlet is a single, central servlet that receives all incoming requests for your application. Its job is to figure out which of your controller methods should handle the request. Think of it as the traffic cop for your entire application.
  • A Controller is a class you write that contains the methods (or "handlers") for specific endpoints.

The diagram below shows the high-level flow. A request comes in, the DispatcherServlet intercepts it, and based on the URL and HTTP method, it dispatches the request to the appropriate method in one of your controllers.

Spring MVC Request Lifecycle Diagram
A detailed view of the Spring MVC request lifecycle. For now, focus on the path from Request (1) -> DispatcherServlet -> HandlerMapping (2) -> Controller (4). This is the core routing mechanism.

2. Creating a REST Controller with @RestController

To tell Spring that a class is a controller, you use an annotation. For building REST APIs, the most common annotation is @RestController.

@RestController is a convenience annotation that combines two others:

  1. @Controller: Marks the class as a web controller, making it eligible for detection by the DispatcherServlet.
  2. @ResponseBody: Tells Spring that the return value of a method should be automatically serialized into the response body (typically as JSON). This saves you from manually converting your Java objects to JSON. In Express, this is similar to what res.json() does for you.

Let's watch a short video that introduces these core controller annotations.

Spring Annotations Explained: Comprehensive Guide with Examples

The video 'Spring Annotations Explained' from CodeSnippet provides a clear, visual explanation of how the DispatcherServlet finds controllers and what the @RestController annotation does.

Watch from 00:44 to 03:23 to understand the role of @Controller and the request flow, then watch from 05:36 to 07:02 to see how @RestController simplifies building REST APIs by combining @Controller and @ResponseBody.


3. Mapping Requests with @GetMapping and @PostMapping

Once you have a @RestController, you need to define which methods handle which requests. This is done with mapping annotations.

  • @GetMapping("/path"): Maps HTTP GET requests for /path to the annotated method.
  • @PostMapping("/path"): Maps HTTP POST requests for /path to the annotated method.

These are direct equivalents to app.get('/path', ...) and app.post('/path', ...) in Express. Other annotations like @PutMapping, @DeleteMapping, and @PatchMapping also exist.

Spring Framework Request Handling Flowchart
This flowchart shows how an incoming request is routed through Spring's annotations. The request goes to a `@RestController`, is matched by a mapping like `@GetMapping`, and the method processes it.

Let's see this in action with an official Spring guide.

Getting Started | Building a RESTful Web Service

The official Spring guide 'Building a RESTful Web Service' is the classic 'Hello, World!' for Spring APIs. It perfectly demonstrates the concepts we've just discussed.

Read the sections 'Create a Resource Representation Class' and 'Create a Resource Controller'. You don't need to code along just yet, but focus on the structure of the GreetingController.java file. Notice how it uses @RestController on the class and @GetMapping on the method.


4. Hands-On: Building Your First Endpoints

Now, let's apply this to our Blog Platform. We will create a BlogController and define our first two endpoints.

Step 1: Create the Controller Class

In your IDE, navigate to your main application package (e.g., com.blogplatform) and create a new sub-package named controller. Inside this new package, create a new Java class called BlogController.

Step 2: Add Annotations and GET Endpoint

Modify BlogController.java with the following code:

package com.blogplatform.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class BlogController {

    @GetMapping("/api/posts")
    public List<String> getAllPosts() {
        // For now, we return static data.
        // In a real application, this would come from a database.
        return List.of("My First Blog Post", "Learning Spring Boot");
    }
}

MERN Comparison:
This is the Spring Boot equivalent of the following Express.js code, which you are very familiar with from your work with the MERN stack.

// In your Express routes file
const express = require('express');
const router = express.Router();

router.get('/api/posts', (req, res) => {
  const posts = ["My First Blog Post", "Learning Spring Boot"];
  res.json(posts);
});

module.exports = router;

Notice the parallels:

Spring Boot Express.js Description
@RestController express.Router() + res.json() Defines a set of routes that will return JSON.
@GetMapping("/api/posts") router.get('/api/posts', ...) Maps a GET request on a specific path to a handler function.
public List<String>... res.json(posts) The return value is automatically serialized to a JSON response.

Step 3: Run and Test the GET Endpoint

Run your Spring Boot application. Once it has started, open a terminal and use curl or open Postman to make a GET request:

curl http://localhost:8080/api/posts

You should see the following JSON response:

["My First Blog Post","Learning Spring Boot"]

Congratulations, you've just created your first working API endpoint in Spring Boot!

Step 4: Add a POST Endpoint

Now, let's add an endpoint to handle creating a new post. We won't actually save anything yet; we'll just return a success message.

Add the following method to your BlogController.java:

// Inside the BlogController class, below the getAllPosts method

@PostMapping("/api/posts")
public String createPost() {
    return "Post created successfully!";
}

It's perfectly fine to have @GetMapping and @PostMapping listen on the same path (/api/posts). The DispatcherServlet knows which method to call based on the HTTP verb (GET vs. POST).

Step 5: Run and Test the POST Endpoint

Restart your application. Now, use Postman to send a POST request to http://localhost:8080/api/posts. You should see the string Post created successfully! in the response body.

The following video demonstrates testing GET and POST endpoints using Postman, which is a great tool for this purpose.

#15 Spring Web Http methods GET and POST

The video '#15 Spring Web Http methods GET and POST' by Telusko shows how to use Postman to test different HTTP methods and explains the logic of mapping endpoints.

Watch the segment from 01:26 to 04:54 to get a refresher on HTTP methods and see how Postman is set up. Then, watch 14:45 to 15:41, where he specifically explains how GET and POST mappings can coexist on the same URL path, just like we did.


Conclusion

In this lesson, you successfully built your first REST controller in Spring Boot. You saw how the concepts of routing and request handling from your MERN background translate directly to Spring's annotation-driven model.

Key Takeaways:

  • @RestController is your primary tool for creating classes that handle API requests and return JSON.
  • @GetMapping and @PostMapping are specific, clean annotations for mapping requests to your Java methods, just like app.get() and app.post() in Express.
  • The DispatcherServlet is the central component that routes incoming requests to the correct controller method.
  • Spring Boot automatically handles the serialization of your Java objects (like a List) into JSON, thanks to the Jackson library running under the hood.

Preview of the Next Lesson:
Our controller currently contains placeholder logic (List.of(...)). In a real application, this is bad practice. The controller's job is only to handle the HTTP request and response, not to perform business logic.

In our next lesson, we will implement a service layer to contain business logic and inject it into the controller. This will be your first practical application of the Dependency Injection principles we've discussed, and a crucial step towards building a clean, scalable, and testable application architecture.