spring-boot-rest-api-standards
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.
Best use case
spring-boot-rest-api-standards is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
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.
Teams using spring-boot-rest-api-standards should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/spring-boot-rest-api-standards/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How spring-boot-rest-api-standards Compares
| Feature / Agent | spring-boot-rest-api-standards | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
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.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# Spring Boot REST API Standards
This skill provides comprehensive guidance for building RESTful APIs in Spring Boot applications with consistent design patterns, proper error handling, validation, and architectural best practices based on REST principles and Spring Boot conventions.
## Overview
Spring Boot REST API standards establish consistent patterns for building production-ready REST APIs. These standards cover resource-based URL design, proper HTTP method usage, status code conventions, DTO patterns, validation, error handling, pagination, security headers, and architectural layering. Implement these patterns to ensure API consistency, maintainability, and adherence to REST principles.
## When to Use This Skill
Use this skill when:
- Creating new REST endpoints and API routes
- Designing request/response DTOs and API contracts
- Planning HTTP methods and status codes
- Implementing error handling and validation
- Setting up pagination, filtering, and sorting
- Designing security headers and CORS policies
- Implementing HATEOAS (Hypermedia As The Engine Of Application State)
- Reviewing REST API architecture and design patterns
- Building microservices with consistent API standards
- Documenting API endpoints with clear contracts
## Instructions
### To Build RESTful API Endpoints
Follow these steps to create well-designed REST API endpoints:
1. **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
2. **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)
3. **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
4. **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
5. **Implement Validation**
- Use `@Valid` annotation on `@RequestBody` parameters
- Apply validation constraints (`@NotBlank`, `@Email`, `@Size`, etc.)
- Handle validation errors with `MethodArgumentNotValidException`
6. **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
7. **Configure Pagination**
- Use Pageable for large datasets
- Include page, size, sort parameters
- Return metadata with total elements, totalPages, etc.
8. **Add Security Headers**
- Configure CORS policies
- Set content security policy
- Include X-Frame-Options, X-Content-Type-Options
## Examples
### Basic CRUD Controller
```java
@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
```java
// 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
```java
@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
```java
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
private final EmailService emailService;
// Dependencies are explicit and testable
}
```
### 2. Prefer Immutable DTOs
```java
// Java records (JDK 16+)
public record UserResponse(Long id, String name, String email, LocalDateTime createdAt) {}
// Lombok @Value for immutability
@Value
public class UserResponse {
Long id;
String name;
String email;
LocalDateTime createdAt;
}
```
### 3. Validate Input Early
```java
@PostMapping
public ResponseEntity<UserResponse> createUser(@Valid @RequestBody CreateUserRequest request) {
// Validation happens automatically before method execution
return ResponseEntity.status(HttpStatus.CREATED).body(userService.create(request));
}
```
### 4. Use ResponseEntity Flexibly
```java
return ResponseEntity.status(HttpStatus.CREATED)
.header("Location", "/api/users/" + created.getId())
.header("X-Total-Count", String.valueOf(userService.count()))
.body(created);
```
### 5. Implement Proper Transaction Management
```java
@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);
}
}
```
### 6. Add Meaningful Logging
```java
@Slf4j
@Service
public class UserService {
public User create(User user) {
log.info("Creating user with email: {}", user.getEmail());
return userRepository.save(user);
}
}
```
### 7. Document APIs with Javadoc
```java
/**
* Retrieves a user by id.
*
* @param id the user id
* @return ResponseEntity containing a UserResponse
* @throws ResponseStatusException with 404 if user not found
*/
@GetMapping("/{id}")
public ResponseEntity<UserResponse> getUserById(@PathVariable Long id)
```
## Constraints and Warnings
### 1. Never Expose Entities Directly
Use DTOs to separate API contracts from domain models. This prevents accidental exposure of internal data structures and allows API evolution without database schema changes.
### 2. Follow REST Conventions Strictly
- Use nouns for resource names, not verbs
- Use correct HTTP methods for operations
- Use plural resource names (/users, not /user)
- Return appropriate HTTP status codes for each operation
### 3. Handle All Exceptions Globally
Use @RestControllerAdvice to catch all exceptions consistently. Don't let raw exceptions bubble up to clients.
### 4. Always Paginate Large Result Sets
For GET endpoints that might return many results, implement pagination to prevent performance issues and DDoS vulnerabilities.
### 5. Validate All Input Data
Never trust client input. Use Jakarta validation annotations on all request DTOs to validate data at the controller boundary.
### 6. Use Constructor Injection Exclusively
Avoid field injection (`@Autowired`) for better testability and explicit dependency declaration.
### 7. Keep Controllers Thin
Controllers should only handle HTTP request/response adaptation. Delegate business logic to service layers.
### 8. API Versioning
Always version APIs from the start (e.g., `/v1/users`) to allow future changes without breaking existing clients.
### 9. Sensitive Data Protection
Never log or expose sensitive data (passwords, tokens, PII) in API responses or logs.
## 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 APIsRelated Skills
code-standards
Setup universal code quality standards in your project. Use when the user wants to generate coding standards files (CLAUDE.md, AGENTS.md, GEMINI.md, etc.) or mentions 'code standards', 'code review setup', or similar intent in any language.
bootstrap
Wake up, orient, and warm the context with foundational MOOLLM knowledge
academic-writing-standards
Expert knowledge of academic writing standards for peer-reviewed papers, including citation integrity, style compliance, clarity, and scientific writing best practices. Use when reviewing or editing academic manuscripts, papers, or research documentation.
arweave-standards
GitHub repository skill for ArweaveTeam/arweave-standards
springfield-max
Simpsons-themed autonomous workflow orchestrator v7.0 for platform building. Powered by Opus 4.6 Agent Teams, 1M context, adaptive thinking, and effort levels. 17 characters, full MCP access, 50 iteration limits, orchestrator promises, and mandatory quality gates. Domain-agnostic - works for any software platform.
spring-validation
Bean Validation (Jakarta Validation) with Spring Boot. Custom validators, validation groups, cross-field validation, and internationalized error messages.
spring-boot-project-creator
Creates and scaffolds a new Spring Boot project (3.x or 4.x) by downloading from Spring Initializr, generating package structure (DDD or Layered architecture), configuring JPA, SpringDoc OpenAPI, and Docker Compose services (PostgreSQL, Redis, MongoDB). Use when creating a new Java Spring Boot project from scratch, bootstrapping a microservice, or initializing a backend application.
spring-boot-performance
Guide for optimizing Spring Boot application performance including caching, pagination, async processing, and JPA optimization. Use this when addressing performance issues or implementing high-traffic features.
spring-boot-event-driven-patterns
Implement Event-Driven Architecture (EDA) in Spring Boot using ApplicationEvent, @EventListener, and Kafka. Use for building loosely-coupled microservices with domain events, transactional event listeners, and distributed messaging patterns.
spring-boot-engineer
Use when building Spring Boot 3.x applications, microservices, or reactive Java applications. Invoke for Spring Data JPA, Spring Security 6, WebFlux, Spring Cloud integration.
restcontroller-conventions
Specifies standards for RestController classes, including API route mappings, HTTP method annotations, dependency injection, and error handling with ApiResponse and GlobalExceptionHandler.
NestJS API Standards
Response wrapping, pagination, and error standardization.