Skillversitas

Request & Response Body

Introduction

Spring Boot makes it easy to read data from HTTP requests and to build structured responses. Learn how to use @RequestBody, @ModelAttribute, @RequestHeader, and ResponseEntity.

@RequestBody

Used to read JSON (or XML) from the request body and convert it into a Java object. Spring uses Jackson for the automatic conversion.

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

Request:

POST /api/users
Content-Type: application/json

{
  "name": "John",
  "email": "[email protected]"
}

@ModelAttribute

Used to read data from forms (application/x-www-form-urlencoded). Ideal for HTML form submissions.

@PostMapping("/register")
public ResponseEntity<User> register(@ModelAttribute UserForm form) {
    User user = userService.convertAndSave(form);
    return ResponseEntity.status(HttpStatus.CREATED).body(user);
}

Differences between @RequestBody and @ModelAttribute:

Feature @RequestBody @ModelAttribute
Content type JSON / XML form-urlencoded
Parsing Jackson Spring MVC binding
Best for REST API HTML forms
Default Required Required

@RequestHeader

Used to get values from HTTP headers.

@PostMapping("/login")
public ResponseEntity<?> login(
        @RequestBody LoginRequest request,
        @RequestHeader("User-Agent") String userAgent,
        @RequestHeader(value = "X-Forwarded-For", required = false) String ip) {
    return ResponseEntity.ok(userService.login(request, userAgent, ip));
}

ResponseEntity for Custom Responses

ResponseEntity gives you full control over the status, headers, and body.

@GetMapping("/export")
public ResponseEntity<byte[]> exportData() {
    byte[] file = reportService.generatePdf();
    return ResponseEntity.ok()
        .contentType(MediaType.APPLICATION_PDF)
        .header("Content-Disposition", "attachment; filename=report.pdf")
        .body(file);
}
@GetMapping("/{id}")
public ResponseEntity<User> getById(@PathVariable Long id) {
    return userService.findById(id)
        .map(user -> ResponseEntity.ok(user))
        .orElse(ResponseEntity.notFound().build());
}

HTTP Status Codes

Code Name Use Case
200 OK Success
201 Created Data was created successfully
204 No Content Success, without a body
400 Bad Request Invalid input
404 Not Found Resource not found
500 Internal Server Error Error on the server
@PutMapping("/{id}")
public ResponseEntity<User> update(@PathVariable Long id, @RequestBody User user) {
    if (!userService.existsById(id)) {
        return ResponseEntity.notFound().build();
    }
    User updated = userService.update(id, user);
    return ResponseEntity.ok(updated);
}

Content Negotiation

Spring supports multiple response formats based on the Accept header.

@GetMapping(value = "/{id}", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
public User getById(@PathVariable Long id) {
    return userService.findById(id);
}

Summary

  • @RequestBody for JSON input, @ModelAttribute for forms.
  • ResponseEntity gives you full control over the response.
  • Content negotiation allows JSON or XML responses.

Next chapter: We'll cover Data Validation — how to make sure input from the client follows business rules using Bean Validation.