npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@gen2code/api-framework

v1.0.4

Published

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

Downloads

9

Readme

@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

pnpm add @gen2code/api-framework

Quick Start

Basic Usage

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

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

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

// Validate user data
const userData = {
  id: 'user_123',
  email: '[email protected]',
  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:

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

{
  "success": true,
  "data": {
    "id": "user_123",
    "email": "[email protected]",
    "name": "John Doe"
  },
  "meta": {
    "timestamp": "2024-01-01T00:00:00Z",
    "requestId": "req_abc123",
    "version": "1.0.0"
  }
}

Error Response Example

{
  "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:

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:

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:

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

// Login request validation
const loginData = LoginRequestSchema.parse({
  email: '[email protected]',
  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:

// 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:

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.