Java · OOP, JVM and backend craft
How do you build a REST API with Spring?
Short answer
Spring MVC maps HTTP requests to controller methods and serializes responses. Good REST APIs use explicit status codes, validated DTOs and centralized error handling.
@RestController combines @Controller and @ResponseBody, so return values are serialized, usually to JSON. @RequestMapping sets the base path, and method-level annotations map HTTP verbs and path variables.
@RestController
@RequestMapping("/api/orders")
public class OrderController {
private final OrderService service;
public OrderController(OrderService service) {
this.service = service;
}
@GetMapping("/{id}")
public ResponseEntity<OrderResponse> get(@PathVariable long id) {
return service.find(id)
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}
}What separates a good API
- Use nouns for resources and HTTP verbs for actions
- Return 201 with a Location header when creating a resource
- Use 400 for validation errors, 404 for missing resources and 409 for conflicts
- Validate request bodies with @Valid and bean validation annotations
- Centralize error mapping with @ControllerAdvice and a consistent error shape
- Do not expose JPA entities directly; use request and response DTOs
Make writes idempotent where possible, especially for retries and message delivery. For large collections, paginate and document the contract. Version or evolve APIs deliberately rather than changing response fields in place.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What status code should a successful create return?
- 2How do you handle validation errors consistently?
- 3Why should controllers return DTOs instead of entities?
- 4What makes an HTTP endpoint idempotent?
Say it in the interview
I map resources with @RestController and method annotations, bind path and query parameters, validate request DTOs, and return ResponseEntity so the status code is explicit. I keep controllers thin and put business rules and transactions in services. Errors go through a ControllerAdvice so every failure has the same shape. I avoid exposing entities, and I paginate collection endpoints and design writes to be retry-safe.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Java mock interview and get scored feedback on depth, clarity and confidence.