API Controller

1 min read

REST API Controller

Use a REST controller only for the GitHub Pages path in Java Spring Hacks.

  • @RestController returns response data as JSON.
  • @RequestMapping("/api/data") gives this controller an /api/* prefix.
  • @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping define HTTP operations.
  • ResponseEntity<T> combines a typed response body with an HTTP status.
@RestController
@RequestMapping("/api/data")
public class DataApiController {
    private final DataRepository repository;

    public DataApiController(DataRepository repository) {
        this.repository = repository;
    }

    @GetMapping
    public ResponseEntity<List<Data>> getAll() {
        return ResponseEntity.ok(repository.findAll());
    }
}

The /api/* filter chain is configured in SecurityConfig.java with Order(1). It is stateless and must allow the GitHub Pages origin through CORS. For server-rendered HTML and forms, use the separate /mvc/* path instead.

Course Timeline