Skip to content

docs: add comprehensive API documentation and standardize error handling #30

@phrazzld

Description

@phrazzld

Description

API endpoints lack comprehensive documentation and standardized error handling, violating our principles of Explicit is Better than Implicit and Consistent Error Handling.

Philosophy Violation

Core Principle: API Design - Define clear, explicit, robust contracts for all APIs with documented inputs, outputs, behavior, and errors.

Reference: DEVELOPMENT_PHILOSOPHY.md Section "Architecture Guidelines": "Define explicit contracts for all APIs. Use OpenAPI (Swagger) for REST as the source of truth."

Issues Found

1. Missing API Documentation

  • No OpenAPI/Swagger specification for REST endpoints
  • API contracts not formally defined
  • Input/output schemas not documented
  • Error response formats not standardized

2. Inconsistent Error Handling

  • API routes may have inconsistent error response formats
  • Error messages not structured consistently
  • Missing proper HTTP status codes for different error types

3. Current API Structure Needs Documentation

// Endpoints that need documentation:
GET  /api/quotes
POST /api/quotes
GET  /api/quotes/[id]
PUT  /api/quotes/[id]
DELETE /api/quotes/[id]

GET  /api/readings
POST /api/readings
GET  /api/readings/[id]
PUT  /api/readings/[id]
DELETE /api/readings/[id]

Required Implementation

1. OpenAPI Specification

Create docs/api/openapi.yaml with complete API documentation:

openapi: 3.0.0
info:
  title: Vanity API
  version: 1.0.0
  description: Personal reading and quote management API

paths:
  /api/quotes:
    get:
      summary: List quotes with filtering and pagination
      parameters:
        - name: search
          in: query
          schema:
            type: string
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 10
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/QuotesResponse'
        '400':
          description: Bad request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

2. Standardized Error Response Schema

interface ErrorResponse {
  error: {
    code: string;           // Machine-readable error code
    message: string;        // Human-readable error message
    details?: unknown;      // Additional error context
    timestamp: string;      // ISO 8601 timestamp
    correlation_id: string; // Request tracing ID
  };
}

3. Consistent Error Handling Middleware

// src/app/api/middleware/errorHandler.ts
export function withErrorHandler(handler: ApiHandler) {
  return async (req: NextRequest) => {
    try {
      return await handler(req);
    } catch (error) {
      return standardizeApiError(error);
    }
  };
}

Acceptance Criteria

Documentation Requirements

  • Create comprehensive OpenAPI 3.0 specification
  • Document all request/response schemas
  • Include examples for all endpoints
  • Document authentication/authorization requirements
  • Add error response documentation with status codes

Error Handling Standards

  • Implement standardized error response format
  • Use appropriate HTTP status codes consistently
  • Include correlation IDs in all error responses
  • Sanitize error messages (no sensitive data exposure)
  • Add structured logging for all API errors

Implementation

  • Add OpenAPI documentation generation to build process
  • Create reusable error handling middleware
  • Update all API routes to use standardized patterns
  • Add API documentation to development setup guide
  • Include API testing examples

Validation

  • Validate API responses match OpenAPI specification
  • Test error handling scenarios comprehensively
  • Verify documentation accuracy with automated tests
  • Ensure consistent behavior across all endpoints

Benefits

  • Developer Experience: Clear API contracts and examples
  • Error Handling: Consistent, debuggable error responses
  • Integration: Easier for frontend and external integrations
  • Observability: Structured error logging and tracing
  • Maintenance: Self-documenting API changes

Implementation Phases

  1. Phase 1: Create OpenAPI specification for existing endpoints
  2. Phase 2: Implement standardized error handling middleware
  3. Phase 3: Update all API routes to use new patterns
  4. Phase 4: Add documentation generation to CI/CD pipeline
  5. Phase 5: Add API contract testing

Priority

Medium - Important for API usability and maintainability, especially as the application grows.

Metadata

Metadata

Assignees

Labels

priority:mediumMedium priority items for future planningsize:MMedium: 3 points - Feature enhancements, refactoringtype:docsDocumentation improvements

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions