Your first REST controller

Spring Boot · lesson 9 of 39 · 4 min read

Map HTTP verbs and paths to methods, and control status codes and response bodies.

Open this lesson in the learning hub

Key points

  • @RestController = @Controller + @ResponseBody: return values are serialised straight to JSON by Jackson.
  • @RequestMapping on the class sets the base path; @GetMapping and friends set the verb.
  • @PathVariable reads a path segment, @RequestParam reads a query string value.
  • Return the object for a plain 200. Return ResponseEntity when you need a status or headers.
  • Use the right verbs: POST creates and answers 201 with a Location header, PUT replaces, DELETE answers 204.
  • Keep controllers thin — parse, delegate, respond. Business rules belong in the service.

Example

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

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    private final OrderService service;

    public OrderController(OrderService service) {
        this.service = service;
    }

    @GetMapping("/{id}")
    public OrderResponse byId(@PathVariable long id) {
        return service.find(id);          // 200 + JSON body
    }

    @GetMapping
    public List<OrderResponse> search(@RequestParam(defaultValue = "0") int page) {
        return service.page(page);
    }

    @PostMapping
    public ResponseEntity<OrderResponse> create(@RequestBody CreateOrderRequest req) {
        OrderResponse created = service.create(req);
        return ResponseEntity
                .created(URI.create("/api/orders/" + created.id()))
                .body(created);           // 201 + Location header
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void cancel(@PathVariable long id) {
        service.cancel(id);               // 204, empty body
    }
}

A controller maps HTTP to method calls — nothing more should live in it.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Spring Boot course, and every lesson in it is listed on the Spring Boot contents page.