npm package: @gen2code/api-framework
Description: OpenAPI specification, documentation standards, and API patterns for the Gen2Code framework
Author: WebHouse
Latest version: 1.0.4

# @gen2code/api-framework

OpenAPI specification, documentation standards, and API patterns for the Gen2Code framework.

## Overview

The API Framework component establishes the foundational API architecture, documentation standards, and development patterns for the Gen2Code framework. It provides OpenAPI specifications, API documentation generation, request/response schemas, and standardized API patterns that all other components must follow.

## Features

- **OpenAPI 3.0 Specification**: Complete API documentation with interactive Swagger UI
- **Request/Response Schemas**: Comprehensive Zod schemas for validation
- **Standardized Error Handling**: Consistent error codes and response formats
- **Authentication Schemas**: JWT, OAuth, and API key authentication patterns
- **Validation Middleware**: Express middleware for request validation
- **Pagination Support**: Built-in pagination and filtering utilities
- **TypeScript Support**: Full TypeScript definitions and type safety

## Installation

```bash
pnpm add @gen2code/api-framework
```

## Quick Start

### Basic Usage

```typescript
import {
  ApiResponseSchema,
  createSuccessResponse,
  createErrorResponse,
  validateBody,
  LoginRequestSchema,
  ApiErrorCode
} from '@gen2code/api-framework';

// Create a success response
const response = createSuccessResponse(
  { id: '1', name: 'John Doe' },
  {
    timestamp: new Date().toISOString(),
    requestId: 'req_123',
    version: '1.0.0'
  }
);

// Create an error response
const errorResponse = createErrorResponse(
  {
    code: ApiErrorCode.VALIDATION_ERROR,
    message: 'Invalid input data',
    details: { email: 'Invalid email format' }
  },
  {
    timestamp: new Date().toISOString(),
    requestId: 'req_123',
    version: '1.0.0'
  }
);
```

### Express Middleware

```typescript
import express from 'express';
import {
  validateBody,
  validateQuery,
  ValidationMiddleware,
  LoginRequestSchema,
  PaginationQuerySchema
} from '@gen2code/api-framework';

const app = express();

// Validate login request body
app.post('/auth/login', 
  validateBody(LoginRequestSchema),
  (req, res) => {
    // req.body is now validated and typed
    const { email, password } = req.body;
    // Handle login logic
  }
);

// Validate pagination query parameters
app.get('/users',
  ValidationMiddleware.pagination(),
  (req, res) => {
    // req.query is now validated with defaults applied
    const { page, limit, sort, search } = req.query;
    // Handle user listing with pagination
  }
);
```

### Schema Validation

```typescript
import {
  UserSchema,
  validateSafe,
  ApiErrorCode
} from '@gen2code/api-framework';

// Validate user data
const userData = {
  id: 'user_123',
  email: 'john@example.com',
  name: 'John Doe',
  role: 'member',
  permissions: ['read:users'],
  createdAt: '2024-01-01T00:00:00Z',
  updatedAt: '2024-01-01T00:00:00Z'
};

const result = validateSafe(UserSchema, userData);

if (result.success) {
  console.log('Valid user:', result.data);
} else {
  console.error('Validation errors:', result.errors);
}
```

## API Response Format

All API responses follow a standardized format:

```typescript
interface ApiResponse<T = any> {
  success: boolean;
  data?: T;
  error?: {
    code: string;
    message: string;
    details?: Record<string, any>;
  };
  meta: {
    timestamp: string;
    requestId: string;
    version: string;
    pagination?: {
      page: number;
      limit: number;
      total: number;
      totalPages: number;
      hasNext: boolean;
      hasPrev: boolean;
    };
  };
}
```

### Success Response Example

```json
{
  "success": true,
  "data": {
    "id": "user_123",
    "email": "john@example.com",
    "name": "John Doe"
  },
  "meta": {
    "timestamp": "2024-01-01T00:00:00Z",
    "requestId": "req_abc123",
    "version": "1.0.0"
  }
}
```

### Error Response Example

```json
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid email format",
    "details": {
      "field": "email",
      "value": "invalid-email"
    }
  },
  "meta": {
    "timestamp": "2024-01-01T00:00:00Z",
    "requestId": "req_abc123",
    "version": "1.0.0"
  }
}
```

## Error Codes

The framework provides standardized error codes organized by category:

### Authentication Errors (AUTH_xxx)
- `AUTH_001`: Unauthorized
- `AUTH_002`: Invalid Token
- `AUTH_003`: Token Expired
- `AUTH_004`: Insufficient Permissions

### Validation Errors (VAL_xxx)
- `VAL_001`: Validation Error
- `VAL_002`: Missing Required Field
- `VAL_003`: Invalid Format
- `VAL_004`: Value Out of Range

### Resource Errors (RES_xxx)
- `RES_001`: Resource Not Found
- `RES_002`: Resource Already Exists
- `RES_003`: Resource Conflict
- `RES_004`: Resource Locked

### System Errors (SYS_xxx)
- `SYS_001`: Internal Server Error
- `SYS_002`: Service Unavailable
- `SYS_003`: Rate Limit Exceeded
- `SYS_004`: Maintenance Mode

## Validation Middleware

The framework provides several validation middleware functions:

```typescript
import {
  validateBody,
  validateQuery,
  validateParams,
  validateHeaders,
  ValidationMiddleware,
  CommonValidationSchemas
} from '@gen2code/api-framework';

// Validate request body
app.post('/users', validateBody(UserSchema), handler);

// Validate query parameters
app.get('/users', validateQuery(PaginationQuerySchema), handler);

// Validate route parameters
app.get('/users/:id', ValidationMiddleware.idParam(), handler);

// Validate with custom schema
app.post('/custom', validateBody(z.object({
  name: z.string().min(1),
  age: z.number().min(0)
})), handler);
```

## Pagination

Built-in pagination support with metadata:

```typescript
import {
  createPaginationMetadata,
  validatePagination
} from '@gen2code/api-framework';

// Create pagination metadata
const pagination = createPaginationMetadata(1, 20, 100);
// Result: { page: 1, limit: 20, total: 100, totalPages: 5, hasNext: true, hasPrev: false }

// Validate pagination query
const query = validatePagination({ page: '2', limit: '50' });
// Result: { page: 2, limit: 50 }
```

## Authentication Schemas

Pre-built schemas for common authentication patterns:

```typescript
import {
  LoginRequestSchema,
  RegisterRequestSchema,
  AuthResponseSchema,
  JWTTokenSchema,
  ApiKeySchema
} from '@gen2code/api-framework';

// Login request validation
const loginData = LoginRequestSchema.parse({
  email: 'user@example.com',
  password: 'securepassword',
  rememberMe: true
});

// API key validation
const apiKey = ApiKeySchema.parse({
  id: 'key_123',
  name: 'Production API Key',
  keyPreview: 'pk_live_...',
  permissions: ['read:users', 'write:posts'],
  rateLimit: 1000,
  createdAt: '2024-01-01T00:00:00Z',
  updatedAt: '2024-01-01T00:00:00Z'
});
```

## OpenAPI Integration

The package includes a complete OpenAPI 3.0 specification:

```typescript
// Access the OpenAPI specification
import { readFileSync } from 'fs';
import { join } from 'path';

const openApiSpec = readFileSync(
  join(__dirname, '../openapi/base.yaml'),
  'utf-8'
);
```

## TypeScript Support

Full TypeScript support with comprehensive type definitions:

```typescript
import type {
  ApiResponse,
  User,
  Team,
  PaginationQuery,
  ValidationOptions
} from '@gen2code/api-framework';

// Type-safe API responses
const response: ApiResponse<User> = createSuccessResponse(user, meta);

// Type-safe pagination
const query: PaginationQuery = { page: 1, limit: 20 };
```

## Contributing

This package is part of the Gen2Code framework. Please refer to the main repository for contribution guidelines.

## License

MIT License - see the main repository for details.