Spring Boot REST Controller

A REST controller is the entry point for all incoming HTTP requests. It receives a request, calls the right service, and sends back a response — usually in JSON format.

What REST Means

REST (Representational State Transfer) is a style for building APIs. It uses standard HTTP methods to perform operations on data.

HTTP Method    Action          Example URL
───────────    ─────────────   ─────────────────────────
GET            Read data       GET /users
POST           Create data     POST /users
PUT            Replace data    PUT /users/1
PATCH          Update part     PATCH /users/1
DELETE         Delete data     DELETE /users/1

Creating Your First REST Controller

@RestController                       ← Marks this class as a REST API controller
@RequestMapping("/users")             ← Base URL for all methods in this class
public class UserController {

    private final UserService userService;

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

    @GetMapping                       ← GET /users
    public List<User> getAllUsers() {
        return userService.findAll();
    }

    @GetMapping("/{id}")              ← GET /users/1
    public User getUserById(@PathVariable Long id) {
        return userService.findById(id);
    }

    @PostMapping                      ← POST /users
    public User createUser(@RequestBody User user) {
        return userService.save(user);
    }

    @DeleteMapping("/{id}")           ← DELETE /users/1
    public void deleteUser(@PathVariable Long id) {
        userService.delete(id);
    }
}

What @RestController Does

@RestController
    │
    ├── @Controller     ← Registers class as Spring MVC controller
    └── @ResponseBody   ← Converts return value to JSON automatically

Without @ResponseBody, Spring tries to find a view (HTML template). With it, Spring serializes the return value directly to JSON using Jackson.

Request Lifecycle Diagram

Browser / Mobile App
        │
        │  HTTP Request: GET /users/5
        ▼
  DispatcherServlet     ← Spring's front controller — routes all requests
        │
        ▼
  UserController
  getUserById(5)
        │
        ▼
  UserService
  findById(5)
        │
        ▼
  UserRepository
  findById(5)
        │
        ▼
  Database → returns User object
        │
        ▼
  Jackson converts User → JSON
        │
        ▼
  HTTP Response: {"id":5,"name":"Alice",...}
        │
        ▼
  Browser / Mobile App

Returning HTTP Status Codes

By default, Spring returns 200 OK. Use ResponseEntity to control the status code explicitly:

@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
    User saved = userService.save(user);
    return ResponseEntity.status(HttpStatus.CREATED).body(saved);
    //                              ↑ 201 Created
}

@GetMapping("/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
    return userService.findById(id)
        .map(ResponseEntity::ok)                     // 200 OK
        .orElse(ResponseEntity.notFound().build());  // 404 Not Found
}

Common HTTP Status Codes

Code    Meaning               When to Use
─────   ───────────────────   ────────────────────────────────
200     OK                    Successful GET, PUT, PATCH
201     Created               Successful POST (new resource)
204     No Content            Successful DELETE
400     Bad Request           Invalid input from client
401     Unauthorized          Not logged in
403     Forbidden             Logged in but no permission
404     Not Found             Resource does not exist
500     Internal Server Error Unexpected error on server

Returning JSON vs Plain Text

Return Type          What Spring Sends
──────────────────   ──────────────────────────────────
String               Plain text: Hello
User object          JSON: {"id":1,"name":"Alice"}
List<User>           JSON array: [{"id":1,...},{...}]
ResponseEntity<T>    Full control: body + status + headers
void                 Empty response (204 No Content)

Summary

  • @RestController marks a class to handle HTTP requests and return JSON
  • Use @GetMapping, @PostMapping, @PutMapping, @DeleteMapping for each HTTP method
  • @RequestMapping on the class sets the base URL for all methods
  • Use ResponseEntity to control the HTTP status code in the response
  • Spring converts your return objects to JSON automatically using Jackson

Leave a Comment

Your email address will not be published. Required fields are marked *