Claude
Skills
Sign in
Back

api-documentation

Included with Lifetime
$97 forever

Production-grade skill for API documentation creation including OpenAPI/Swagger specifications, REST endpoint documentation, authentication flows, and error handling guides.

Backend & APIsscriptsassets

What this skill does


# API Documentation Skill v2.0

## Skill Identity

```yaml
skill_id: api-documentation
type: specialized_skill
domain: technical_documentation
responsibility: Generate and validate API documentation
atomicity: single-purpose
```

## Input/Output Schemas

### Input Schema

```typescript
interface APIDocInput {
  // Required
  api_type: 'rest' | 'graphql' | 'websocket' | 'grpc';

  // Source information
  source?: {
    openapi_spec?: string;       // Existing OpenAPI spec
    code_files?: string[];       // Source code to analyze
    endpoint_list?: Endpoint[];  // Manual endpoint definitions
  };

  // Output preferences
  output_format?: 'openapi' | 'asyncapi' | 'markdown' | 'html';
  openapi_version?: '3.0.0' | '3.1.0';

  // Content options
  include_examples?: boolean;
  include_error_codes?: boolean;
  include_authentication?: boolean;
  include_rate_limiting?: boolean;

  // Authentication
  authentication_type?: 'bearer' | 'api_key' | 'oauth2' | 'basic' | 'none';

  // Metadata
  api_info?: {
    title: string;
    version: string;
    description?: string;
    contact?: ContactInfo;
    license?: LicenseInfo;
  };
}

interface Endpoint {
  method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
  path: string;
  summary: string;
  description?: string;
  parameters?: Parameter[];
  request_body?: RequestBody;
  responses: Response[];
  tags?: string[];
}
```

### Output Schema

```typescript
interface APIDocOutput {
  status: 'success' | 'partial_success' | 'failed';

  // Generated content
  content: {
    specification?: string;      // OpenAPI/AsyncAPI spec
    markdown?: string;           // Markdown documentation
    html?: string;               // HTML documentation
  };

  // Validation results
  validation: {
    is_valid: boolean;
    errors: ValidationError[];
    warnings: ValidationWarning[];
  };

  // Quality metrics
  quality: {
    completeness_score: number;  // 0-100
    example_coverage: number;    // 0-100
    error_coverage: number;      // 0-100
  };

  // Execution metadata
  metadata: {
    endpoints_documented: number;
    schemas_generated: number;
    examples_created: number;
    processing_time_ms: number;
  };
}
```

## Parameter Validation Rules

```yaml
validation_rules:
  api_type:
    type: string
    required: true
    enum: [rest, graphql, websocket, grpc]
    error_message: "api_type must be one of: rest, graphql, websocket, grpc"

  output_format:
    type: string
    required: false
    default: openapi
    enum: [openapi, asyncapi, markdown, html]
    conditional:
      - if: api_type == 'websocket'
        then: default = 'asyncapi'

  openapi_version:
    type: string
    required: false
    default: "3.1.0"
    pattern: "^3\\.(0|1)\\.\\d+$"

  api_info.title:
    type: string
    required: true
    min_length: 3
    max_length: 100

  api_info.version:
    type: string
    required: true
    pattern: "^\\d+\\.\\d+\\.\\d+$"
    error_message: "Version must follow semver format (e.g., 1.0.0)"
```

## Retry Logic

```typescript
async function executeWithRetry<T>(
  operation: () => Promise<T>,
  config: RetryConfig
): Promise<T> {
  let lastError: Error;
  let delay = config.backoff.initial_delay_ms;

  for (let attempt = 1; attempt <= config.max_attempts; attempt++) {
    try {
      return await operation();
    } catch (error) {
      lastError = error;

      // Check if error is retryable
      if (!isRetryableError(error)) {
        throw error;
      }

      // Log retry attempt
      log.warn({
        skill: 'api-documentation',
        attempt,
        max_attempts: config.max_attempts,
        delay_ms: delay,
        error: error.message
      });

      if (attempt < config.max_attempts) {
        await sleep(delay);
        delay = Math.min(
          delay * config.backoff.multiplier,
          config.backoff.max_delay_ms
        );
      }
    }
  }

  throw new SkillExecutionError(
    'API_DOC_GENERATION_FAILED',
    `Failed after ${config.max_attempts} attempts`,
    lastError
  );
}

function isRetryableError(error: Error): boolean {
  const retryableCodes = [
    'RATE_LIMITED',
    'TIMEOUT',
    'TEMPORARY_FAILURE',
    'SERVICE_UNAVAILABLE'
  ];
  return retryableCodes.includes(error.code);
}
```

## Logging & Observability Hooks

### Pre-Execution Hook

```typescript
function preExecutionHook(input: APIDocInput, context: ExecutionContext): void {
  // Log invocation start
  log.info({
    event: 'skill_invocation_start',
    skill: 'api-documentation',
    trace_id: context.trace_id,
    span_id: context.span_id,
    input_summary: {
      api_type: input.api_type,
      output_format: input.output_format,
      endpoint_count: input.source?.endpoint_list?.length ?? 0
    }
  });

  // Start metrics collection
  metrics.startTimer('api_doc_generation_duration');
  metrics.increment('api_doc_invocations_total', {
    api_type: input.api_type
  });

  // Validate input
  const validation = validateInput(input);
  if (!validation.valid) {
    log.error({
      event: 'input_validation_failed',
      errors: validation.errors
    });
    throw new ValidationError(validation.errors);
  }
}
```

### Post-Execution Hook

```typescript
function postExecutionHook(
  output: APIDocOutput,
  context: ExecutionContext,
  duration: number
): void {
  // Log completion
  log.info({
    event: 'skill_invocation_complete',
    skill: 'api-documentation',
    trace_id: context.trace_id,
    status: output.status,
    metrics: {
      duration_ms: duration,
      endpoints_documented: output.metadata.endpoints_documented,
      quality_score: output.quality.completeness_score
    }
  });

  // Record metrics
  metrics.stopTimer('api_doc_generation_duration');
  metrics.record('api_doc_quality_score', output.quality.completeness_score);
  metrics.increment('api_doc_completions_total', {
    status: output.status
  });

  // Alert on quality issues
  if (output.quality.completeness_score < 70) {
    log.warn({
      event: 'low_quality_output',
      score: output.quality.completeness_score,
      issues: output.validation.warnings
    });
  }
}
```

### Error Hook

```typescript
function errorHook(
  error: Error,
  context: ExecutionContext,
  input: APIDocInput
): void {
  log.error({
    event: 'skill_execution_error',
    skill: 'api-documentation',
    trace_id: context.trace_id,
    error: {
      code: error.code,
      message: error.message,
      stack: error.stack
    },
    input_summary: {
      api_type: input.api_type,
      output_format: input.output_format
    }
  });

  metrics.increment('api_doc_errors_total', {
    error_code: error.code
  });
}
```

## OpenAPI 3.1 Specification Template

```yaml
openapi: 3.1.0
info:
  title: ${api_info.title}
  version: ${api_info.version}
  description: ${api_info.description}
  contact:
    name: ${api_info.contact.name}
    email: ${api_info.contact.email}
  license:
    name: ${api_info.license.name}
    url: ${api_info.license.url}

servers:
  - url: https://api.example.com/v1
    description: Production server
  - url: https://staging-api.example.com/v1
    description: Staging server

paths:
  /resources:
    get:
      operationId: listResources
      summary: List all resources
      description: Retrieve a paginated list of all resources
      tags:
        - Resources
      parameters:
        - $ref: '#/components/parameters/PageParam'
        - $ref: '#/components/parameters/LimitParam'
        - $ref: '#/components/parameters/SortParam'
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ResourceList'
              examples:
                success:
                  $ref: '#/components/examples/ResourceListExample'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '500':
          $ref: '#/component

Related in Backend & APIs