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
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:
curl -s localhost:8080/api/hello
echo
curl -s "localhost:8080/api/hello?name=Linh"
echo
curl -s localhost:8080/api/languagesHello, world!
Hello, Linh!
["Java","Kotlin","Groovy"]
Note: The
echolines only add a newline between responses —curl -sprints 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.
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;
}
}curl -s -i localhost:8080/api/tasksHTTP/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:
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?
- Security checks
- An implied
@ResponseBodyon every handler method - Automatic database access
- Support for HTTP/3
A handler returns List<Task>. What does the client receive?
- The result of
toString() - A JSON array produced by Jackson
- A Java serialized byte stream
- An HTML table
How do you make the query parameter name optional with a fallback value?
@RequestParam String name = "world"@RequestParam(defaultValue = "world") String name@Optional String name@PathVariable("world") String name