@RequestBody & ResponseEntity — Spring Technical Interview Questions & Answers

Reading JSON bodies and shaping HTTP responses.

@RequestBody & ResponseEntity

  • @RequestBody reads JSON into a Java object; ResponseEntity lets you control status and body.
  • @RequestBody User user — JSON payload becomes a User.
  • ResponseEntity.ok(data) or status(201).body(saved).
  • Useful for returning 201 Created, 404 Not Found, etc. with a body.
  • Body in, status+body out.

Technical Interview Tip: When to return ResponseEntity instead of a raw object.

Code Examples for @RequestBody & ResponseEntity

@RequestBody & ResponseEntity — working example

import java.util.Map;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
class UserController {

  @GetMapping("/{id}")
  ResponseEntity<String> get(@PathVariable Long id) {
    return ResponseEntity.ok("user-" + id);
  }

  @GetMapping
  String byRole(@RequestParam(defaultValue = "user") String role) {
    return "role=" + role;
  }

  @PostMapping
  ResponseEntity<String> create(@RequestBody Map<String, String> body) {
    return ResponseEntity.status(201).body("created:" + body.get("email"));
  }
}

@RequestBody & ResponseEntity — @RestController = API JSON/text; @PathVariable from URI, @RequestParam from query, @RequestBody from JSON body.

How to Explain @RequestBody & ResponseEntity to an Interviewer

What is @RequestBody & ResponseEntity (sb rest)?

Used for GET /api/marks/{roll} a campus API Not just the heading

Give one small example of @RequestBody & ResponseEntity (sb rest).

@RestController + service call Reading JSON bodies and shaping HTTP responses

What mistake do beginners make with @RequestBody & ResponseEntity (sb rest)?

business logic inside the controller Show the fix

Where do you use @RequestBody & ResponseEntity (sb rest)?

a campus API GET /api/marks/{roll}