Spring Boot REST API Standards
Overview
REST API design standards for Spring Boot covering URL design, HTTP methods, status codes, DTOs, validation, error handling, pagination, and security headers.
When to Use
- Creating REST endpoints and API routes
- Designing DTOs and API contracts
- Implementing error handling and validation
- Setting up pagination and filtering
- Configuring security headers and CORS
- Reviewing REST API architecture
Instructions
To Build RESTful API Endpoints
Follow these steps to create well-designed REST API endpoints:
Design Resource-Based URLs
- Use plural nouns for resource names
- Follow REST conventions: GET /users, POST /users, PUT /users/{id}
- Avoid action-based URLs like /getUserList
Implement Proper HTTP Methods
- GET: Retrieve resources (safe, idempotent)
- POST: Create resources (not idempotent)
- PUT: Replace entire resources (idempotent)
- PATCH: Partial updates (not idempotent)
- DELETE: Remove resources (idempotent)
Use Appropriate Status Codes
- 200 OK: Successful GET/PUT/PATCH
- 201 Created: Successful POST with Location header
- 204 No Content: Successful DELETE
- 400 Bad Request: Invalid request data
- 404 Not Found: Resource doesn't exist
- 409 Conflict: Duplicate resource
- 500 Internal Server Error: Unexpected errors
Create Request/Response DTOs
- Separate API contracts from domain entities
- Use Java records or Lombok
@Data/@Value
- Apply Jakarta validation annotations
- Keep DTOs immutable when possible
Implement Validation
- Use
@Valid annotation on @RequestBody parameters
- Apply validation constraints (
@NotBlank, @Email, @Size, etc.)
- Handle validation errors with
MethodArgumentNotValidException
Set Up Error Handling
- Use
@RestControllerAdvice for global exception handling
- Return standardized error responses with status, error, message, and timestamp
- Use
ResponseStatusException for specific HTTP status codes
Configure Pagination
- Use Pageable for large datasets
- Include page, size, sort parameters
- Return metadata with total elements, totalPages, etc.
Add Security Headers
- Configure CORS policies
- Set content security policy
- Include X-Frame-Options, X-Content-Type-Options
Validation checkpoints:
- After step 1-2: Verify URL structure follows REST conventions (/users not /getUsers)
- After step 3: Test each endpoint returns correct status codes
- After step 4-5: Validate DTOs with curl or HTTPie before proceeding
- After step 6: Confirm error responses match standardized format
Examples
Basic CRUD Controller
@RestController
@RequestMapping("/v1/users")
@RequiredArgsConstructor
@Slf4j
public class UserController {
private final UserService userService;
@GetMapping
public ResponseEntity<Page<UserResponse>> getAllUsers(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int pageSize) {
log.debug("Fetching users page {} size {}", page, pageSize);
Page<UserResponse> users = userService.getAll(page, pageSize);
return ResponseEntity.ok(users);
}
@GetMapping("/{id}")
public ResponseEntity<UserResponse> getUserById(@PathVariable Long id) {
return ResponseEntity.ok(userService.getById(id));
}
@PostMapping
public ResponseEntity<UserResponse> createUser(@Valid @RequestBody CreateUserRequest request) {
UserResponse created = userService.create(request);
return ResponseEntity.status(HttpStatus.CREATED).body(created);
}
@PutMapping("/{id}")
public ResponseEntity<UserResponse> updateUser(
@PathVariable Long id,
@Valid @RequestBody UpdateUserRequest request) {
return ResponseEntity.ok(userService.update(id, request));
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
userService.delete(id);
return ResponseEntity.noContent().build();
}
}
Request/Response DTOs
// Request DTO
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CreateUserRequest {
@NotBlank(message = "User name cannot be blank")
private String name;
@Email(message = "Valid email required")
private String email;
}
// Response DTO
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserResponse {
private Long id;
private String name;
private String email;
private LocalDateTime createdAt;
}
Global Exception Handler
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidationException(
MethodArgumentNotValidException ex, WebRequest request) {
String errors = ex.getBindingResult().getFieldErrors().stream()
.map(f -> f.getField() + ": " + f.getDefaultMessage())
.collect(Collectors.joining(", "));
ErrorResponse errorResponse = new ErrorResponse(
HttpStatus.BAD_REQUEST.value(),
"Validation Error",
"Validation failed: " + errors,
request.getDescription(false).replaceFirst("uri=", "")
);
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(ResponseStatusException.class)
public ResponseEntity<ErrorResponse> handleResponseStatusException(
ResponseStatusException ex, WebRequest request) {
ErrorResponse error = new ErrorResponse(
ex.getStatusCode().value(),
ex.getStatusCode().toString(),
ex.getReason(),
request.getDescription(false).replaceFirst("uri=", "")
);
return new ResponseEntity<>(error, ex.getStatusCode());
}
}
Best Practices
1. Use Constructor Injection
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
}
2. Prefer Immutable DTOs (Java Records or @Value)
public record UserResponse(Long id, String name, String email) {}
3. Implement Proper Transaction Management
@Service
@Transactional
public class UserService {
@Transactional(readOnly = true)
public Optional<User> findById(Long id) { return userRepository.findById(id); }
@Transactional
public User create(User user) { return userRepository.save(user); }
}
Constraints and Warnings
- Never expose entities directly - Use DTOs to separate API contracts from domain models
- Follow REST conventions - Use nouns for resources (/users), correct HTTP methods, plural names, proper status codes
- Handle all exceptions globally - Use
@RestControllerAdvice, never let raw exceptions bubble up
- Always paginate large result sets - Prevent performance issues and DDoS vulnerabilities
- Validate all input data - Use Jakarta validation annotations on request DTOs
- Never expose sensitive data - Don't log or expose passwords, tokens, PII
References
- See
references/ directory for comprehensive reference material including HTTP status codes, Spring annotations, and detailed examples
- Refer to the
developer-kit-java:spring-boot-code-review-expert agent for code review guidelines
- Review
spring-boot-dependency-injection/SKILL.md for dependency injection patterns
- Check
../spring-boot-test-patterns/SKILL.md for testing REST APIs
1---
2name: spring-boot-rest-api-standards
3description: Provides REST API design standards and best practices for Spring Boot projects. Use when creating or reviewing REST endpoints, DTOs, error handling, pagination, security headers, HATEOAS and architecture patterns.
4allowed-tools: Read, Write, Edit, Bash, Glob, Grep
5metadata:
6 source: https://skillmd.com/skills/aibot88/spring-boot-rest-api-standards
7---
8
9# Spring Boot REST API Standards
10
11## Overview
12
13REST API design standards for Spring Boot covering URL design, HTTP methods, status codes, DTOs, validation, error handling, pagination, and security headers.
14
15## When to Use
16
17- Creating REST endpoints and API routes
18- Designing DTOs and API contracts
19- Implementing error handling and validation
20- Setting up pagination and filtering
21- Configuring security headers and CORS
22- Reviewing REST API architecture
23
24## Instructions
25
26### To Build RESTful API Endpoints
27
28Follow these steps to create well-designed REST API endpoints:
29
301. **Design Resource-Based URLs**
31 - Use plural nouns for resource names
32 - Follow REST conventions: GET /users, POST /users, PUT /users/{id}
33 - Avoid action-based URLs like /getUserList
34
352. **Implement Proper HTTP Methods**
36 - GET: Retrieve resources (safe, idempotent)
37 - POST: Create resources (not idempotent)
38 - PUT: Replace entire resources (idempotent)
39 - PATCH: Partial updates (not idempotent)
40 - DELETE: Remove resources (idempotent)
41
423. **Use Appropriate Status Codes**
43 - 200 OK: Successful GET/PUT/PATCH
44 - 201 Created: Successful POST with Location header
45 - 204 No Content: Successful DELETE
46 - 400 Bad Request: Invalid request data
47 - 404 Not Found: Resource doesn't exist
48 - 409 Conflict: Duplicate resource
49 - 500 Internal Server Error: Unexpected errors
50
514. **Create Request/Response DTOs**
52 - Separate API contracts from domain entities
53 - Use Java records or Lombok `@Data`/`@Value`
54 - Apply Jakarta validation annotations
55 - Keep DTOs immutable when possible
56
575. **Implement Validation**
58 - Use `@Valid` annotation on `@RequestBody` parameters
59 - Apply validation constraints (`@NotBlank`, `@Email`, `@Size`, etc.)
60 - Handle validation errors with `MethodArgumentNotValidException`
61
626. **Set Up Error Handling**
63 - Use `@RestControllerAdvice` for global exception handling
64 - Return standardized error responses with status, error, message, and timestamp
65 - Use `ResponseStatusException` for specific HTTP status codes
66
677. **Configure Pagination**
68 - Use Pageable for large datasets
69 - Include page, size, sort parameters
70 - Return metadata with total elements, totalPages, etc.
71
728. **Add Security Headers**
73 - Configure CORS policies
74 - Set content security policy
75 - Include X-Frame-Options, X-Content-Type-Options
76
77**Validation checkpoints:**
78- After step 1-2: Verify URL structure follows REST conventions (/users not /getUsers)
79- After step 3: Test each endpoint returns correct status codes
80- After step 4-5: Validate DTOs with curl or HTTPie before proceeding
81- After step 6: Confirm error responses match standardized format
82
83## Examples
84
85### Basic CRUD Controller
86
87```java
88@RestController
89@RequestMapping("/v1/users")
90@RequiredArgsConstructor
91@Slf4j
92public class UserController {
93 private final UserService userService;
94
95 @GetMapping
96 public ResponseEntity<Page<UserResponse>> getAllUsers(
97 @RequestParam(defaultValue = "0") int page,
98 @RequestParam(defaultValue = "10") int pageSize) {
99 log.debug("Fetching users page {} size {}", page, pageSize);
100 Page<UserResponse> users = userService.getAll(page, pageSize);
101 return ResponseEntity.ok(users);
102 }
103
104 @GetMapping("/{id}")
105 public ResponseEntity<UserResponse> getUserById(@PathVariable Long id) {
106 return ResponseEntity.ok(userService.getById(id));
107 }
108
109 @PostMapping
110 public ResponseEntity<UserResponse> createUser(@Valid @RequestBody CreateUserRequest request) {
111 UserResponse created = userService.create(request);
112 return ResponseEntity.status(HttpStatus.CREATED).body(created);
113 }
114
115 @PutMapping("/{id}")
116 public ResponseEntity<UserResponse> updateUser(
117 @PathVariable Long id,
118 @Valid @RequestBody UpdateUserRequest request) {
119 return ResponseEntity.ok(userService.update(id, request));
120 }
121
122 @DeleteMapping("/{id}")
123 public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
124 userService.delete(id);
125 return ResponseEntity.noContent().build();
126 }
127}
128```
129
130### Request/Response DTOs
131
132```java
133// Request DTO
134@Data
135@NoArgsConstructor
136@AllArgsConstructor
137public class CreateUserRequest {
138 @NotBlank(message = "User name cannot be blank")
139 private String name;
140
141 @Email(message = "Valid email required")
142 private String email;
143}
144
145// Response DTO
146@Data
147@NoArgsConstructor
148@AllArgsConstructor
149public class UserResponse {
150 private Long id;
151 private String name;
152 private String email;
153 private LocalDateTime createdAt;
154}
155```
156
157### Global Exception Handler
158
159```java
160@RestControllerAdvice
161@Slf4j
162public class GlobalExceptionHandler {
163
164 @ExceptionHandler(MethodArgumentNotValidException.class)
165 public ResponseEntity<ErrorResponse> handleValidationException(
166 MethodArgumentNotValidException ex, WebRequest request) {
167 String errors = ex.getBindingResult().getFieldErrors().stream()
168 .map(f -> f.getField() + ": " + f.getDefaultMessage())
169 .collect(Collectors.joining(", "));
170
171 ErrorResponse errorResponse = new ErrorResponse(
172 HttpStatus.BAD_REQUEST.value(),
173 "Validation Error",
174 "Validation failed: " + errors,
175 request.getDescription(false).replaceFirst("uri=", "")
176 );
177 return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
178 }
179
180 @ExceptionHandler(ResponseStatusException.class)
181 public ResponseEntity<ErrorResponse> handleResponseStatusException(
182 ResponseStatusException ex, WebRequest request) {
183 ErrorResponse error = new ErrorResponse(
184 ex.getStatusCode().value(),
185 ex.getStatusCode().toString(),
186 ex.getReason(),
187 request.getDescription(false).replaceFirst("uri=", "")
188 );
189 return new ResponseEntity<>(error, ex.getStatusCode());
190 }
191}
192```
193
194## Best Practices
195
196### 1. Use Constructor Injection
197```java
198@Service
199@RequiredArgsConstructor
200public class UserService {
201 private final UserRepository userRepository;
202}
203```
204
205### 2. Prefer Immutable DTOs (Java Records or `@Value`)
206```java
207public record UserResponse(Long id, String name, String email) {}
208```
209
210### 3. Implement Proper Transaction Management
211```java
212@Service
213@Transactional
214public class UserService {
215 @Transactional(readOnly = true)
216 public Optional<User> findById(Long id) { return userRepository.findById(id); }
217
218 @Transactional
219 public User create(User user) { return userRepository.save(user); }
220}
221```
222
223## Constraints and Warnings
224
2251. **Never expose entities directly** - Use DTOs to separate API contracts from domain models
2262. **Follow REST conventions** - Use nouns for resources (/users), correct HTTP methods, plural names, proper status codes
2273. **Handle all exceptions globally** - Use `@RestControllerAdvice`, never let raw exceptions bubble up
2284. **Always paginate large result sets** - Prevent performance issues and DDoS vulnerabilities
2295. **Validate all input data** - Use Jakarta validation annotations on request DTOs
2306. **Never expose sensitive data** - Don't log or expose passwords, tokens, PII
231
232## References
233
234- See `references/` directory for comprehensive reference material including HTTP status codes, Spring annotations, and detailed examples
235- Refer to the `developer-kit-java:spring-boot-code-review-expert` agent for code review guidelines
236- Review `spring-boot-dependency-injection/SKILL.md` for dependency injection patterns
237- Check `../spring-boot-test-patterns/SKILL.md` for testing REST APIs