Best practices for writing REST APIs in Java
Here are the best practices for writing REST APIs in Java (especially using Spring Boot) — covering everything from design to security and performance.
✅ 1. Use Proper HTTP Methods
HTTP Method | Purpose | Example |
---|---|---|
GET |
Read data | /users/1 |
POST |
Create new resource | /users |
PUT |
Update entire resource | /users/1 |
PATCH |
Update part of resource | /users/1 |
DELETE |
Delete resource | /users/1 |
✅ 2. Use Meaningful Resource Names (Nouns)
-
❌
/getUserData
-
✅
/users/{id}
Use plural nouns for consistency:
/users
/users/1/orders
/products/123/reviews
✅ 3. Use Proper HTTP Status Codes
Status Code | Meaning |
---|---|
200 OK |
Request successful |
201 Created |
Resource created (POST) |
204 No Content |
Deleted or updated with no return body |
400 Bad Request |
Invalid input |
401 Unauthorized |
Missing/invalid credentials |
403 Forbidden |
Not allowed |
404 Not Found |
Resource not found |
500 Internal Server Error |
Server crash |
✅ 4. Use Request Validation
Use @Valid
and constraint annotations:
@PostMapping("/users")
public ResponseEntity<?> createUser(@RequestBody @Valid UserDto user) {
...
}
public class UserDto {
@NotBlank private String name;
@Email private String email;
}
✅ 5. Consistent Response Format (Use Wrapper)
Instead of returning raw data, wrap it:
public class ApiResponse<T> {
private boolean success;
private T data;
private String message;
}
This makes frontend parsing easier and adds standard error handling.
✅ 6. Version Your APIs
Put version in URL:
/api/v1/users
This helps when making backward-incompatible changes in the future.
✅ 7. Use Pagination for Large Lists
Use query params:
GET /users?page=2&size=10
Spring Data makes this easy:
@GetMapping("/users")
public Page<User> getUsers(Pageable pageable) { ... }
✅ 8. Proper Error Handling
Use @ControllerAdvice
and @ExceptionHandler
:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<ApiResponse<?>> handleNotFound(UserNotFoundException ex) {
return ResponseEntity.status(404).body(new ApiResponse<>(false, null, ex.getMessage()));
}
}
✅ 9. Secure APIs (JWT, OAuth2, HTTPS)
-
Use HTTPS for all endpoints
-
Implement JWT token-based auth for stateless security
-
Use Spring Security for role-based access control
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin/users")
public List<User> listAdmins() { ... }
✅ 10. Use OpenAPI / Swagger Documentation
Auto-generate API docs using Swagger:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
</dependency>
Then access:
http://localhost:8080/swagger-ui.html
✅ 11. Avoid Business Logic in Controller
Keep controllers thin — move logic to @Service
classes:
@RestController
public class UserController {
@Autowired private UserService service;
...
}
✅ 12. Use Logging (not System.out.println
)
Use SLF4J/Logback:
private static final Logger log = LoggerFactory.getLogger(MyController.class);
log.info("Fetching user {}", id);
log.error("User not found: {}", id);
✅ 13. Use DTOs — Don't Expose Entities
Never expose JPA entities directly in API responses:
-
Prevents overfetching
-
Prevents leaking internal structure
-
Helps with versioning
public class UserDto {
private String name;
private String email;
}
✅ 14. Cache Responses When Appropriate
Use Spring's cache abstraction:
@Cacheable("products")
public Product getProductById(Long id) { ... }
✅ 15. Test Your API
-
Write unit tests with
@WebMvcTest
-
Write integration tests with
@SpringBootTest
@WebMvcTest(UserController.class)
public class UserControllerTest {
@Autowired MockMvc mockMvc;
...
}
🧠 Summary Table
Category | Best Practice |
---|---|
HTTP Usage | Use correct verbs & status codes |
Structure | Use nouns, versioning, DTOs |
Validation | Use @Valid , @NotNull , etc. |
Security | Use HTTPS, JWT, @PreAuthorize |
Documentation | Use Swagger/OpenAPI |
Error Handling | Use @ControllerAdvice |
Performance | Use pagination & caching |
Clean Code | Thin controllers, service layer logic |
Let me know if you'd like:
-
A working sample project with all best practices
-
A PDF checklist
-
REST API interview questions based on these practices
Comments
Post a Comment