Building a CRUD REST API — Spring Technical Interview Questions & Answers
A full Create/Read/Update/Delete controller example.
Building a CRUD REST API
- CRUD means Create, Read, Update, Delete for a resource.
- POST create, GET read, PUT/PATCH update, DELETE remove.
- Controller calls service; service calls repository.
- Validate input and return correct status codes.
- Walk through one resource end-to-end across layers.
Technical Interview Tip: Describe one entity CRUD with four endpoints.
Code Examples for Building a CRUD REST API
Building a CRUD REST API — 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"));
}
}Building a CRUD REST API — @RestController = API JSON/text; @PathVariable from URI, @RequestParam from query, @RequestBody from JSON body.
How to Explain Building a CRUD REST API to an Interviewer
What is Building a CRUD REST API (sb example)?
Used for GET /api/marks/{roll} a campus API Not just the heading
Give one small example of Building a CRUD REST API (sb example).
@RestController + service call A full Create/Read/Update/Delete controller example
What mistake do beginners make with Building a CRUD REST API (sb example)?
business logic inside the controller Show the fix
Where do you use Building a CRUD REST API (sb example)?
a campus API GET /api/marks/{roll}