TExcelTAD
Home › Spring Boot › Your First REST Controller

Your First REST Controller

A controller is the class that receives HTTP requests. In a REST API, controller methods return Java objects and Spring turns them into JSON automatically. In this lesson you build a small read-only endpoint and call it with curl.

@RestController and @GetMapping

java
package com.example.tasks.hello;

import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/api/hello")
    public String hello(@RequestParam(defaultValue = "world") String name) {
        return "Hello, " + name + "!";
    }

    @GetMapping("/api/languages")
    public List<String> languages() {
        return List.of("Java", "Kotlin", "Groovy");
    }
}
Piece Meaning
@RestController a @Controller whose method results are written directly into the response body
@GetMapping("/api/hello") this method handles GET /api/hello
@RequestParam reads the query parameter ?name=...; defaultValue makes it optional
return String sent as plain text (text/plain)
return List, record, object serialised to JSON by Jackson (application/json)

Restart the app and try it:

bash · try it yourself
curl -s localhost:8080/api/hello
echo
curl -s "localhost:8080/api/hello?name=Linh"
echo
curl -s localhost:8080/api/languages
Hello, world!
Hello, Linh!
["Java","Kotlin","Groovy"]

Note: The echo lines only add a newline between responses — curl -s prints the body exactly as received, without a trailing newline.

Returning objects as JSON

Records are perfect for response bodies: immutable, concise, and Jackson serialises their components by name.

java
public record Task(long id, String title, boolean done) {}

@RestController
public class TaskController {

    private final List<Task> tasks = List.of(
        new Task(1, "Learn Spring Boot", false),
        new Task(2, "Write a controller", true));

    @GetMapping("/api/tasks")
    public List<Task> all() {
        return tasks;
    }
}
bash · try it yourself
curl -s -i localhost:8080/api/tasks
HTTP/1.1 200
Content-Type: application/json
Transfer-Encoding: chunked
Date: Thu, 16 Oct 2025 02:20:44 GMT

[{"id":1,"title":"Learn Spring Boot","done":false},{"id":2,"title":"Write a controller","done":true}]

The -i flag shows the response headers: status 200, and Content-Type: application/json chosen because the method returned a list of objects.

What Spring does with each request

Under the hood, Spring MVC's DispatcherServlet keeps a table from (HTTP method, path) to handler method. For every request it looks up the handler, calls it and converts the return value. Here is a tiny plain-Java model of that dispatch table:

java · try it yourself
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

record Task(long id, String title, boolean done) {
    String toJson() {
        return "{\"id\":" + id + ",\"title\":\"" + title + "\",\"done\":" + done + "}";
    }
}

class Dispatcher {
    private final Map<String, Function<Map<String, String>, String>> routes = new LinkedHashMap<>();

    void get(String path, Function<Map<String, String>, String> handler) {
        routes.put("GET " + path, handler);
    }

    String handle(String method, String path, Map<String, String> query) {
        var handler = routes.get(method + " " + path);
        if (handler == null) return "404 Not Found";
        return "200 OK " + handler.apply(query);
    }
}

class Main {
    public static void main(String[] args) {
        List<Task> tasks = List.of(new Task(1, "Learn Spring Boot", false));
        Dispatcher d = new Dispatcher();
        d.get("/api/hello", q -> "Hello, " + q.getOrDefault("name", "world") + "!");
        d.get("/api/tasks", q -> "[" + tasks.get(0).toJson() + "]");

        System.out.println(d.handle("GET", "/api/hello", Map.of()));
        System.out.println(d.handle("GET", "/api/hello", Map.of("name", "Linh")));
        System.out.println(d.handle("GET", "/api/tasks", Map.of()));
        System.out.println(d.handle("DELETE", "/api/tasks", Map.of()));
    }
}
200 OK Hello, world!
200 OK Hello, Linh!
200 OK [{"id":1,"title":"Learn Spring Boot","done":false}]
404 Not Found

Real Spring is smarter: a known path called with the wrong method returns 405 Method Not Allowed rather than 404, and it supports path patterns, content negotiation and much more — but the principle is the same lookup table, built automatically from your annotations at startup.

@Controller vs. @RestController

@Controller @RestController
return value is a view name (e.g. a Thymeleaf template) return value is the response body
add @ResponseBody per method to return data @ResponseBody is implied on every method
server-rendered HTML pages JSON APIs

Tip: Keep controllers thin. A controller should translate HTTP into method calls and back; the actual business logic belongs in a service class, which you will meet in the next lessons.

Test yourself

What does @RestController add compared to @Controller?

  1. Security checks
  2. An implied @ResponseBody on every handler method
  3. Automatic database access
  4. Support for HTTP/3

A handler returns List<Task>. What does the client receive?

  1. The result of toString()
  2. A JSON array produced by Jackson
  3. A Java serialized byte stream
  4. An HTML table

How do you make the query parameter name optional with a fallback value?

  1. @RequestParam String name = "world"
  2. @RequestParam(defaultValue = "world") String name
  3. @Optional String name
  4. @PathVariable("world") String name