Junior — Middle
What is the difference between @RequestBody and @ResponseBody annotations in REST API development?
sobes.tech AI
Answer from AI
In Java REST API development, the annotations @RequestBody and @ResponseBody are used for working with the HTTP request and response bodies respectively:
-
@RequestBody indicates that the body of the incoming HTTP request should be converted (deserialized) into a Java object. For example, JSON from the request is automatically converted into an object.
-
@ResponseBody indicates that the value returned by the method should be serialized into the HTTP response body (for example, a Java object is converted into JSON).
Example:
@PostMapping("/users")
public @ResponseBody User createUser(@RequestBody User user) {
// user — object obtained from JSON request
// returning an object that will be converted into JSON response
return userService.save(user);
}