Skip to content
api-guidelines-rfc-39 logo

API Guidelines (RFC-39)

api-guidelines-rfc-39

RFC-39 compliant API best practices for Java services. Covers request/response patterns, error handling, pagination, versioning, and authentication standards. Use when designing or reviewing REST APIs in Java services.

SKILL.md

Full skill instructions

API Guidelines (RFC-39)

RFC-39 compliant API best practices for Java services.

When to use this skill

  • Designing new REST API endpoints
  • Reviewing API implementations for compliance
  • Implementing error handling patterns
  • Setting up pagination and filtering
  • Configuring API versioning
  • Implementing authentication and authorization

Skill Contents

Sections

Available Resources

📚 references/​ - Detailed documentation


Quick Start

1. Controller Setup

@RestController
@RequestMapping("/​api/​v1/​orders")
@RequiredArgsConstructor
public class OrderController {

    private final OrderService orderService;
    private final ResponseFactory responseFactory;

    @GetMapping("/​{orderId}")
    public ResponseEntity<ApiResponse<OrderDto>> getOrder(
            @PathVariable String orderId) {
        OrderDto order = orderService.findById(orderId);
        return responseFactory.ok(order);
    }
}

2. Response Factory

@Component
public class ResponseFactory {

    public <T> ResponseEntity<ApiResponse<T>> ok(T data) {
        return ResponseEntity.ok(ApiResponse.success(data));
    }

    public <T> ResponseEntity<ApiResponse<T>> created(T data) {
        return ResponseEntity.status(HttpStatus.CREATED)
            .body(ApiResponse.success(data));
    }
}

Request/​Response Patterns

Standard Response Envelope

{
  "success": true,
  "data": { ... },
  "meta": {
    "requestId": "abc-123",
    "timestamp": "2026-01-27T12:00:00Z"
  }
}

Java Implementation

@Data
@Builder
public class ApiResponse<T> {
    private boolean success;
    private T data;
    private ApiError error;
    private ApiMeta meta;

    public static <T> ApiResponse<T> success(T data) {
        return ApiResponse.<T>builder()
            .success(true)
            .data(data)
            .meta(ApiMeta.now())
            .build();
    }
}

@Data
@Builder
public class ApiMeta {
    private String requestId;
    private Instant timestamp;

    public static ApiMeta now() {
        return ApiMeta.builder()
            .requestId(MDC.get("requestId"))
            .timestamp(Instant.now())
            .build();
    }
}

Error Handling

Error Response Format

{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request parameters",
    "details": [
      {
        "field": "email",
        "message": "must be a valid email address"
      }
    ]
  },
  "meta": {
    "requestId": "abc-123",
    "timestamp": "2026-01-27T12:00:00Z"
  }
}

Exception Handler

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ApiResponse<Void>> handleNotFound(
            ResourceNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
            .body(ApiResponse.error("NOT_FOUND", ex.getMessage()));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ApiResponse<Void>> handleValidation(
            MethodArgumentNotValidException ex) {
        List<FieldError> details = ex.getBindingResult()
            .getFieldErrors()
            .stream()
            .map(e -> new FieldError(e.getField(), e.getDefaultMessage()))
            .toList();

        return ResponseEntity.badRequest()
            .body(ApiResponse.validationError(details));
    }
}

Standard Error Codes

CodeHTTP StatusDescription
VALIDATION_ERROR400Invalid request parameters
UNAUTHORIZED401Missing or invalid authentication
FORBIDDEN403Insufficient permissions
NOT_FOUND404Resource not found
CONFLICT409Resource conflict
RATE_LIMITED429Too many requests
INTERNAL_ERROR500Unexpected server error

Pagination

Request Parameters

ParameterDefaultDescription
page0Page number (0-indexed)
size20Page size (max 100)
sort-Sort field and direction

Response Format

{
  "success": true,
  "data": [...],
  "meta": {
    "pagination": {
      "page": 0,
      "size": 20,
      "totalElements": 150,
      "totalPages": 8,
      "hasNext": true,
      "hasPrevious": false
    }
  }
}

Controller Example

@GetMapping
public ResponseEntity<ApiResponse<List<OrderDto>>> listOrders(
        @RequestParam(defaultValue = "0") int page,
        @RequestParam(defaultValue = "20") int size,
        @RequestParam(required = false) String sort) {

    Pageable pageable = PageRequest.of(page, Math.min(size, 100));
    Page<OrderDto> orders = orderService.findAll(pageable);

    return responseFactory.paginated(orders);
}

Versioning

URL Path Versioning (Preferred)

@RestController
@RequestMapping("/​api/​v1/​orders")
public class OrderV1Controller { }

@RestController
@RequestMapping("/​api/​v2/​orders")
public class OrderV2Controller { }

Deprecation Headers

@GetMapping("/​legacy-endpoint")
@Deprecated
public ResponseEntity<ApiResponse<Void>> legacyEndpoint() {
    return ResponseEntity.ok()
        .header("Deprecation", "true")
        .header("Sunset", "Sat, 01 Mar 2026 00:00:00 GMT")
        .header("Link", "</​api/​v2/​new-endpoint>; rel=\"successor-version\"")
        .body(ApiResponse.success(null));
}

Authentication

WebAPI Annotation

@RestController
@RequestMapping("/​api/​v1/​orders")
public class OrderController {

    @GetMapping
    @WebAPI(AuthType.PRIVATE)  // Requires user authentication
    public ResponseEntity<...> listOrders() { }

    @GetMapping("/​public-info")
    @WebAPI(AuthType.PUBLIC)   // No authentication required
    public ResponseEntity<...> getPublicInfo() { }

    @GetMapping("/​internal")
    @WebAPI(AuthType.INTERNAL) // Service-to-service only
    public ResponseEntity<...> internalEndpoint() { }
}

Authentication Types

TypeUsage
PRIVATEUser-authenticated endpoints
PUBLICUnauthenticated, public endpoints
INTERNALService-to-service communication

References

ReferenceDescription
references/​response-patterns.mdDetailed response patterns

Related Rules

Related Skills

SkillPurpose
rest-apiREST API implementation
grpc-services-rfc-33gRPC service standards
<!-- AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY --> <!-- Source: bitsoex/​ai-code-instructions → java/​skills/​api-guidelines-rfc-39/​SKILL.md --> <!-- To modify, edit the source file and run the distribution workflow -->

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View