← Learning Hub
Beginner

Your First REST Controller

A controller handles web requests. @RestController means every method returns data (as JSON), not an HTML page.

A controller is the front door of your API: it maps web addresses to Java methods and turns return values into JSON. With a few annotations, Spring handles reading paths and query parameters and converting types.

Example
package com.terixto.shop;

import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api")
public class HelloController {

    record Product(long id, String name, int price) {}

    private final List<Product> products = List.of(
        new Product(1, "Kettle", 1299),
        new Product(2, "Iron", 899),
        new Product(3, "Toaster", 1599));

    @GetMapping("/hello")
    public String hello() {
        return "Hello from Spring Boot";
    }

    @GetMapping("/products")
    public List<Product> all(@RequestParam(defaultValue = "100000") int maxPrice) {
        return products.stream().filter(p -> p.price() <= maxPrice).toList();
    }

    @GetMapping("/products/{id}")
    public Product one(@PathVariable long id) {
        return products.stream().filter(p -> p.id() == id).findFirst().orElseThrow();
    }
}

Try it

Example
curl http://localhost:8080/api/hello
# Hello from Spring Boot

curl "http://localhost:8080/api/products?maxPrice=1300"
# [{"id":1,"name":"Kettle","price":1299},{"id":2,"name":"Iron","price":899}]

curl http://localhost:8080/api/products/3
# {"id":3,"name":"Toaster","price":1599}

The annotations

  • @RequestMapping("/api") on the class - a prefix for every method in it
  • @GetMapping("/path") - handle GET requests (also @PostMapping, @PutMapping, @DeleteMapping)
  • @PathVariable - a part of the path, like {id}
  • @RequestParam - a query parameter, like ?maxPrice=1300; Spring converts the text to int for you
Asking for /api/products/99 here gives an error (500), because orElseThrow() throws. In lesson 5 we'll send a proper 404 instead.
Key points
  • @RestController returns data as JSON.
  • @GetMapping and friends map requests to methods.
  • @PathVariable and @RequestParam read input.

📝 Test yourself

1. What does @RestController do?
2. How do you read {id} from the path?
3. Fill in the annotation for GET requests:
@("/hello")