@RestController — Spring Technical Interview Questions & Answers
Combines @Controller and @ResponseBody for JSON APIs.
@RestController
- @RestController builds JSON APIs easily.
- It is @Controller + @ResponseBody combined.
- Return objects/lists; Boot converts them to JSON.
- Use it for APIs; use @Controller when you return HTML views.
- @RestController = web API controller that writes the response body.
Technical Interview Tip: Contrast @RestController vs @Controller.
Code Examples for @RestController
@RestController — 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"));
}
}@RestController = API JSON/text; @PathVariable from URI, @RequestParam from query, @RequestBody from JSON body.
How to Explain @RestController to an Interviewer
What is @RestController (sb)?
Used for GET /api/marks/{roll} a campus API Not just the heading
Give one small example of @RestController (sb).
@RestController + service call Combines @Controller and @ResponseBody for JSON APIs
What mistake do beginners make with @RestController (sb)?
business logic inside the controller Show the fix
Where do you use @RestController (sb)?
a campus API GET /api/marks/{roll}