What is Spring Boot REST API best practices?
Why Interviewers Ask This
This tests whether you can apply Spring Boot knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
Answer
Best practices for Spring Boot REST APIs: 1. URL design: use nouns, not verbs: /users not /getUsers; use plural: /users/1 not /user/1; hierarchical for relationships: /users/1/orders/5. 2. HTTP status codes: 200 OK (success), 201 Created (POST success), 204 No Content (DELETE, empty response), 400 Bad Request (validation error), 401 Unauthorized (missing auth), 403 Forbidden (insufficient permission), 404 Not Found, 409 Conflict (duplicate), 422 Unprocessable Entity (semantic error), 500 Internal Server Error. 3. Request/response DTOs: never expose JPA entities directly — use DTOs to control what's exposed: record CreateUserRequest(String name, String email) {} record UserResponse(Long id, String name, String email, Instant createdAt) {} @PostMapping public ResponseEntity<UserResponse> create(@Valid @RequestBody CreateUserRequest req) { User user = userService.create(req); return ResponseEntity.status(201).body(mapper.toResponse(user)); }. 4. Consistent error response structure: { "status": 400, "error": "Validation failed", "message": "Name is required", "timestamp": "2024-01-15T10:00:00Z", "path": "/api/users" }. 5. Versioning: URI versioning (/api/v1/users), header versioning (Accept: application/vnd.api.v1+json), or query param (?version=1). 6. Pagination: return page metadata: { "data": [...], "page": 0, "size": 20, "totalElements": 500, "totalPages": 25 }. 7. Idempotency keys: for POST requests that should be idempotent. 8. HATEOAS: Spring HATEOAS for hypermedia links.
Pro Tip
Back up your answer with a specific project or situation. Saying 'In my last Spring Boot project, I used this when...' immediately makes your answer more credible and memorable.
Previous
What is Spring Data JPA query methods and JPQL?
Next
What is Spring Boot JWT authentication implementation?