Easy java spring

How do you build a simple REST endpoint in Spring Boot?

The 30 second answer

I write a class with @RestController and map methods with @GetMapping, @PostMapping and so on. @PathVariable reads a part of the URL, @RequestParam reads a query parameter, and @RequestBody turns the JSON body into a Java object. Whatever the method returns is written back as JSON by Jackson. @RestController is @Controller plus @ResponseBody, so I don't need a view.

<!-- level: 1 --> <!-- must_know: true -->

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

    private final OrderService orders;

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

    @GetMapping("/{id}")                       // GET /api/orders/42
    public OrderDto get(@PathVariable long id) {
        return orders.find(id);
    }

    @GetMapping                                // GET /api/orders?status=PAID
    public List<OrderDto> list(@RequestParam(defaultValue = "ALL") String status) {
        return orders.findByStatus(status);
    }

    @PostMapping                               // POST /api/orders with a JSON body
    public ResponseEntity<OrderDto> create(@Valid @RequestBody CreateOrderRequest request) {
        OrderDto created = orders.create(request);
        return ResponseEntity.created(URI.create("/api/orders/" + created.id())).body(created);
    }
}

What each piece does:

  • @RestController combines @Controller and @ResponseBody, so return values go into the response body instead of naming a view.
  • @RequestMapping on the class sets a base path; @GetMapping, @PostMapping, @PutMapping, @PatchMapping and @DeleteMapping are shortcuts for each HTTP method.
  • @PathVariable binds a URI template variable, @RequestParam binds a query parameter, and @RequestBody reads the body through an HttpMessageConverter (Jackson for JSON).
  • Under the hood, the DispatcherServlet receives every request, finds the matching handler method and calls it. The internals are in What happens internally when you hit a REST endpoint?.
Sources (3)
  1. Spring Framework: Mapping requests (@RequestMapping and shortcuts)docs.spring.io
  2. Spring Framework: @RequestBodydocs.spring.io
  3. Spring Framework: DispatcherServletdocs.spring.io