Skip to content

Spring REST Controller Pattern

Example

java
@RestController
@RequestMapping("/api/users")
public class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/{id}")
    public ResponseEntity<UserDto> getUser(@PathVariable Long id) {
        return ResponseEntity.ok(userService.getUserById(id));
    }
    // ... other endpoints ...
}

Guidelines

  • Annotate with @RestController and use @RequestMapping for base path.
  • Inject services via constructor.
  • Use @GetMapping, @PostMapping, etc. for endpoints.
  • Validate input with @Valid and constraint annotations.
  • Return DTOs, not entities.
  • Use ResponseEntity for flexible responses.

References

Copyright © MSG Systems Romania AI Labs