К основному содержанию
скилл CX Codex

openapi-generator — скилл для Claude Code: OpenAPI из кода

Собирает спецификацию OpenAPI 3.0/3.1 из маршрутов Express, Next.js, Fastify, Hono или NestJS — со схемами, примерами и описаниями.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add patricio0312rev/skills --skill openapi-generator -a claude-code
Открыть на GitHub

Что делает openapi-generator

Скилл проходит по коду и находит определения маршрутов, вытаскивает типы, тела запросов и ответов, параметры. Дальше превращает всё это в объекты путей OpenAPI, собирает компонентные схемы из типов и добавляет описания, примеры и теги. На выходе — файл в YAML или JSON.

Внутри лежат скрипты на TypeScript: конвертер типов в схемы через typescript, сканер маршрутов Express на @babel/parser и @babel/traverse с разбором JSDoc-комментариев (@summary, @description, @tags), генератор спецификации с js-yaml. Базовый шаблон описывает servers, tags, securitySchemes с bearerAuth и apiKey. Готовую спецификацию можно импортировать в Postman или Insomnia либо открыть в Swagger UI.

Сканер Express разбирает JSDoc, поэтому без комментариев над обработчиками summary и теги не появятся — их придётся дописать в спецификацию руками. Конвертер типов понимает примитивы, массивы, объекты и строковые union-типы как enum; на более сложных конструкциях схема выйдет пустой. Проверьте результат перед тем, как отдавать его фронтенду или кодогенерации.

Какие задачи решает

  • собрать спецификацию OpenAPI из уже написанных маршрутов
  • описать схемы запросов и ответов по типам TypeScript
  • добавить примеры и теги в существующую документацию API
  • подготовить файл для импорта в Postman или Insomnia
  • открыть маршруты Express в Swagger UI

Примеры запросов агенту

  • сгенерируй OpenAPI-спецификацию из маршрутов в src/routes
  • сделай swagger spec для API на Fastify, формат YAML
  • добавь описания и теги в OpenAPI-документацию по JSDoc в коде

Как установить openapi-generator

1Через Skills CLI (Vercel)

npx skills add patricio0312rev/skills --skill openapi-generator -a claude-code

2Вручную: положить файлы

~/.claude/skills/openapi-generator/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/openapi-generator/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о openapi-generator

Как установить openapi-generator в Claude?

Выполните npx skills add patricio0312rev/skills --skill openapi-generator -a claude-code. Скилл появится в ~/.claude/skills/openapi-generator/SKILL.md.

Что делает openapi-generator?

Находит маршруты в Express, Next.js, Fastify, Hono или NestJS и собирает из них спецификацию OpenAPI 3.0/3.1 со схемами, примерами и описаниями.

С какими фреймворками работает скилл?

Заявлены Express, Next.js, Fastify, Hono и NestJS. Спецификацию можно импортировать в Postman или Insomnia либо использовать со Swagger UI.

Исходный текст

SKILL.md · MIT
---
name: openapi-generator
description: Generates OpenAPI 3.0/3.1 specifications from Express, Next.js, Fastify, Hono, or NestJS routes. Creates complete specs with schemas, examples, and documentation that can be imported into Postman, Insomnia, or used with Swagger UI. Use when users request "generate openapi", "create swagger spec", "openapi documentation", or "api specification".
---

# OpenAPI Generator

Generate OpenAPI 3.0/3.1 specifications from your API codebase automatically.

## Core Workflow

1. **Scan routes**: Find all API route definitions
2. **Extract schemas**: Types, request/response bodies, params
3. **Build paths**: Convert routes to OpenAPI path objects
4. **Generate schemas**: Create component schemas from types
5. **Add documentation**: Descriptions, examples, tags
6. **Export spec**: YAML or JSON format

## OpenAPI 3.1 Base Template

```yaml
openapi: 3.1.0
info:
  title: API Title
  version: 1.0.0
  description: API description
  contact:
    email: [email protected]
  license:
    name: MIT
    url: https://opensource.org/licenses/MIT

servers:
  - url: http://localhost:3000/api
    description: Development
  - url: https://api.example.com
    description: Production

tags:
  - name: Users
    description: User management endpoints
  - name: Products
    description: Product catalog endpoints

paths: {}

components:
  schemas: {}
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
    apiKey:
      type: apiKey
      in: header
      name: X-API-Key

security:
  - bearerAuth: []
```

## TypeScript to OpenAPI Schema Converter

```typescript
// scripts/type-to-schema.ts
import * as ts from "typescript";

interface OpenAPISchema {
  type?: string;
  properties?: Record<string, OpenAPISchema>;
  required?: string[];
  items?: OpenAPISchema;
  $ref?: string;
  enum?: string[];
  format?: string;
  description?: string;
  example?: unknown;
}

function typeToOpenAPISchema(
  checker: ts.TypeChecker,
  type: ts.Type
): OpenAPISchema {
  // Handle primitives
  if (type.flags & ts.TypeFlags.String) {
    return { type: "string" };
  }
  if (type.flags & ts.TypeFlags.Number) {
    return { type: "number" };
  }
  if (type.flags & ts.TypeFlags.Boolean) {
    return { type: "boolean" };
  }

  // Handle arrays
  if (checker.isArrayType(type)) {
    const elementType = (type as ts.TypeReference).typeArguments?.[0];
    return {
      type: "array",
      items: elementType ? typeToOpenAPISchema(checker, elementType) : {},
    };
  }

  // Handle object types
  if (type.flags & ts.TypeFlags.Object) {
    const properties: Record<string, OpenAPISchema> = {};
    const required: string[] = [];

    type.getProperties().forEach((prop) => {
      const propType = checker.getTypeOfSymbolAtLocation(
        prop,
        prop.valueDeclaration!
      );
      properties[prop.name] = typeToOpenAPISchema(checker, propType);

      // Check if required (no ? modifier)
      if (!(prop.flags & ts.SymbolFlags.Optional)) {
        required.push(prop.name);
      }
    });

    return {
      type: "object",
      properties,
      required: required.length > 0 ? required : undefined,
    };
  }

  // Handle union types (enums)
  if (type.isUnion()) {
    const enumValues = type.types
      .filter((t) => t.isStringLiteral())
      .map((t) => (t as ts.StringLiteralType).value);

    if (enumValues.length > 0) {
      return { type: "string", enum: enumValues };
    }
  }

  return {};
}
```

## Express Route Scanner with JSDoc

```typescript
// scripts/express-openapi.ts
import * as fs from "fs";
import * as path from "path";
import { parse } from "@babel/parser";
import traverse from "@babel/traverse";

interface RouteMetadata {
  method: string;
  path: string;
  summary?: string;
  description?: string;
  tags?: string[];
  requestBody?: object;
  responses?: Record<string, object>;
  parameters?: object[];
  security?: object[];
}

function extractJSDocMetadata(comments: string): Partial<RouteMetadata> {
  const metadata: Partial<RouteMetadata> = {};

  // @summary
  const summaryMatch = comments.match(/@summary\s+(.+)/);
  if (summaryMatch) metadata.summary = summaryMatch[1].trim();

  // @description
  const descMatch = comments.match(/@description\s+(.+)/);
  if (descMatch) metadata.description = descMatch[1].trim();

  // @tags
  const tagsMatch = comments.match(/@tags\s+(.+)/);
  if (tagsMatch) metadata.tags = tagsMatch[1].split(",").map((t) => t.trim());

  return metadata;
}

function scanExpressWithOpenAPI(sourceDir: string): RouteMetadata[] {
  const routes: RouteMetadata[] = [];

  // Implementation: traverse files and extract routes with JSDoc comments
  // Similar to postman generator but with OpenAPI-specific metadata

  return routes;
}
```

## OpenAPI Path Generator

```typescript
// scripts/generate-openapi.ts
import * as yaml from "js-yaml";

interface OpenAPISpec {
  openapi: string;
  info: object;
  servers: object[];
  paths: Record<string, object>;
  components: {
    schemas: Record<string, object>;
    securitySchemes?: object;
  };
  tags?: object[];
  security?: object[];
}

function generateOpenAPISpec(
  routes: RouteMetadata[],
  options: {
    title: string;
    version: string;
    description?: string;
    servers: { url: string; description: string }[];
  }
): OpenAPISpec {
  const spec: OpenAPISpec = {
    openapi: "3.1.0",
    info: {
      title: options.title,
      version: options.version,
      description: options.description,
    },
    servers: options.servers,
    paths: {},
    components: {
      schemas: {},
      securitySchemes: {
        bearerAuth: {
          type: "http",
          scheme: "bearer",
          bearerFormat: "JWT",
        },
      },
    },
    tags: [],
  };

  // Collect unique tags
  const tagSet = new Set<string>();

  // Generate paths
  for (const route of routes) {
    const openAPIPath = route.path.replace(/:(\w+)/g, "{$1}");

    if (!spec.paths[openAPIPath]) {
      spec.paths[openAPIPath] = {};
    }

    spec.paths[openAPIPath][route.method.toLowerCase()] = {
      summary: route.summary || `${route.method} ${route.path}`,
      description: route.description,
      tags: route.tags || [extractResourceTag(route.path)],
      parameters: generateParameters(route),
      requestBody: route.requestBody,
      responses: route.responses || generateDefaultResponses(route.method),
      security: route.security,
    };

    // Collect tags
    (route.tags || [extractResourceTag(route.path)]).forEach((t) =>
      tagSet.add(t)
    );
  }

  // Add tags to spec
  spec.tags = Array.from(tagSet).map((name) => ({ name }));

  return spec;
}

function generateParameters(route: RouteMetadata): object[] {
  const params: object[] = [];

  // Extract path parameters
  const pathParamRegex = /:(\w+)/g;
  let match;

  while ((match = pathParamRegex.exec(route.path)) !== null) {
    params.push({
      name: match[1],
      in: "path",
      required: true,
      schema: { type: "string" },
      description: `${match[1]} parameter`,
    });
  }

  return params;
}

function generateDefaultResponses(method: string): object {
  const responses: Record<string, object> = {
    "200": {
      description: "Successful response",
      content: {
        "application/json": {
          schema: { type: "object" },
        },
      },
    },
    "400": {
      description: "Bad request",
      content: {
        "application/json": {
          schema: { $ref: "#/components/schemas/Error" },
        },
      },
    },
    "401": {
      description: "Unauthorized",
    },
    "404": {
      description: "Not found",
    },
    "500": {
      description: "Internal server error",
    },
  };

  if (method === "POST") {
    responses["201"] = {
      description: "Created successfully",
      content: {
        "application/json": {
          schema: { type: "object" },
        },
      },
    };
  }

  if (method === "DELETE") {
    responses["204"] = {
      description: "Deleted successfully",
    };
  }

  return responses;
}

function extractResourceTag(path: string): string {
  const parts = path.split("/").filter(Boolean);
  return parts[0] || "default";
}
```

## Common Schema Components

```yaml
components:
  schemas:
    Error:
      type: object
      required:
        - code
        - message
      properties:
        code:
          type: string
          example: "VALIDATION_ERROR"
        message:
          type: string
          example: "Invalid request data"
        details:
          type: object
          additionalProperties:
            type: array
            items:
              type: string

    Pagination:
      type: object
      properties:
        page:
          type: integer
          minimum: 1
          example: 1
        limit:
          type: integer
          minimum: 1
          maximum: 100
          example: 10
        total:
          type: integer
          example: 156
        total_pages:
          type: integer
          example: 16

    PaginatedResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        data:
          type: array
          items: {}
        meta:
          $ref: "#/components/schemas/Pagination"

    User:
      type: object
      required:
        - id
        - email
        - name
      properties:
        id:
          type: string
          format: uuid
          example: "123e4567-e89b-12d3-a456-426614174000"
        email:
          type: string
          format: email
          example: "[email protected]"
        name:
          type: string
          example: "John Doe"
        created_at:
          type: string
          format: date-time
          example: "2024-01-15T10:30:00Z"

    CreateUserRequest:
      type: object
      required:
        - email
        - name
        - password
      properties:
        email:
          type: string
          format: email
        name:
          type: string
          minLength: 2
          maxLength: 100
        password:
          type: string
          format: password
          minLength: 8
```

## Fastify Integration

```typescript
// Fastify with @fastify/swagger
import Fastify from "fastify";
import swagger from "@fastify/swagger";
import swaggerUi from "@fastify/swagger-ui";

const fastify = Fastify({ logger: true });

await fastify.register(swagger, {
  openapi: {
    info: {
      title: "My API",
      version: "1.0.0",
    },
    servers: [{ url: "http://localhost:3000" }],
  },
});

await fastify.register(swaggerUi, {
  routePrefix: "/docs",
});

// Routes with schema
fastify.get(
  "/users/:id",
  {
    schema: {
      params: {
        type: "object",
        properties: {
          id: { type: "string", format: "uuid" },
        },
        required: ["id"],
      },
      response: {
        200: {
          type: "object",
          properties: {
            id: { type: "string" },
            name: { type: "string" },
            email: { type: "string" },
          },
        },
      },
    },
  },
  async (request, reply) => {
    // Handler
  }
);
```

## NestJS Integration

```typescript
// NestJS with @nestjs/swagger
import { Controller, Get, Post, Body, Param } from "@nestjs/common";
import { ApiTags, ApiOperation, ApiResponse, ApiBody } from "@nestjs/swagger";

@ApiTags("users")
@Controller("users")
export class UsersController {
  @Get()
  @ApiOperation({ summary: "Get all users" })
  @ApiResponse({ status: 200, description: "List of users", type: [UserDto] })
  findAll() {
    // Implementation
  }

  @Get(":id")
  @ApiOperation({ summary: "Get user by ID" })
  @ApiResponse({ status: 200, description: "User found", type: UserDto })
  @ApiResponse({ status: 404, description: "User not found" })
  findOne(@Param("id") id: string) {
    // Implementation
  }

  @Post()
  @ApiOperation({ summary: "Create new user" })
  @ApiBody({ type: CreateUserDto })
  @ApiResponse({ status: 201, description: "User created", type: UserDto })
  create(@Body() createUserDto: CreateUserDto) {
    // Implementation
  }
}
```

## CLI Script

```typescript
#!/usr/bin/env node
// scripts/openapi-gen.ts
import * as fs from "fs";
import * as yaml from "js-yaml";
import { program } from "commander";

program
  .name("openapi-gen")
  .description("Generate OpenAPI specification from API routes")
  .option("-f, --framework <type>", "Framework (express|nextjs|fastify)", "express")
  .option("-s, --source <path>", "Source directory", "./src")
  .option("-o, --output <path>", "Output file", "./openapi.yaml")
  .option("-t, --title <name>", "API title", "My API")
  .option("-v, --version <version>", "API version", "1.0.0")
  .option("--json", "Output as JSON instead of YAML")
  .parse();

const options = program.opts();

async function main() {
  const routes = await scanRoutes(options.framework, options.source);

  const spec = generateOpenAPISpec(routes, {
    title: options.title,
    version: options.version,
    servers: [
      { url: "http://localhost:3000/api", description: "Development" },
    ],
  });

  const output = options.json
    ? JSON.stringify(spec, null, 2)
    : yaml.dump(spec, { lineWidth: -1 });

  fs.writeFileSync(options.output, output);
  console.log(`Generated ${options.output} with ${routes.length} endpoints`);
}

main();
```

## Validation Script

```typescript
// scripts/validate-openapi.ts
import SwaggerParser from "@apidevtools/swagger-parser";

async function validateSpec(specPath: string): Promise<void> {
  try {
    const api = await SwaggerParser.validate(specPath);
    console.log(`API name: ${api.info.title}, Version: ${api.info.version}`);
    console.log("OpenAPI specification is valid!");
  } catch (err) {
    console.error("Validation failed:", err.message);
    process.exit(1);
  }
}
```

## Best Practices

1. **Use $ref**: Reference shared schemas to avoid duplication
2. **Add examples**: Include realistic examples for all schemas
3. **Document errors**: Define all possible error responses
4. **Use tags**: Organize endpoints by resource/feature
5. **Version control**: Commit spec to repository
6. **Validate**: Run validation before publishing
7. **Generate SDKs**: Use openapi-generator for client SDKs
8. **Serve UI**: Host Swagger UI or Redoc for documentation

## Output Checklist

- [ ] All routes converted to OpenAPI paths
- [ ] Path parameters use {param} syntax
- [ ] Request bodies defined with schemas
- [ ] Response schemas for all status codes
- [ ] Common schemas in components/schemas
- [ ] Security schemes configured
- [ ] Tags applied to all endpoints
- [ ] Examples included for schemas
- [ ] Spec validates without errors
- [ ] YAML/JSON exported successfully

© patricio0312rev · MIT · patricio0312rev/skills

Похожие скиллы

Всё по теме «Бэкенд и API» →
spring-boot-openapi-documentation giuseppe-trisciuoglio Скилл помогает агенту настроить SpringDoc OpenAPI 3.0 и Swagger UI в проекте на Spring Boot 3.x и разметить эндпоинты аннотациями. CX Codex +1 4 000установок api-reference-documentation aj-geddes Скилл помогает агенту собрать справочник по API: эндпоинты, аутентификация, примеры запросов и ответов, спецификация OpenAPI. CX Codex +1 494установок printing-press mvanhorn Автоматизирует создание готовых CLI-утилит на Go по спецификациям OpenAPI, HAR или Postman через цепочку из 21 этапа проверки и сборки. CX Codex +1 7 600установок doc-api davila7 Разбирает код проекта и собирает документацию по API: спецификацию, примеры запросов и ответов, интерактивную страницу. Пригодится, когда эндпоинтов много, а описывать их руками не хочется. 733установок adding-api-docs spencerpauly Скилл собирает OpenAPI/Swagger-описание вашего API: схемы эндпоинтов, типы запросов и ответов, интерактивную страницу документации. CX Codex +1 413установок openapi-spec-generation Seth Hobson Генерирует и поддерживает спецификации OpenAPI 3.1 из кода или design-first описания. Пригодится для документации API, SDK и проверки контрактов. CX Codex 16 374установок

Из того же набора26

mermaid-diagram-generator Скилл рисует диаграммы Mermaid прямо в markdown: блок-схемы, sequence, ERD, состояния и классы. Пригодится, когда нужно показать поток запроса или схему базы в документации. CX Codex +1 331установок visual-regression-tester Скилл настраивает визуальное регрессионное тестирование: снимает скриншоты, сравнивает их с базовыми и ловит случайные изменения интерфейса. CX Codex +1 330установок form-wizard-builder Скилл собирает многошаговые формы: схемы валидации, шаги, общее состояние, индикатор прогресса и шаг проверки перед отправкой. CX Codex +1 328установок skill-creator Скилл, который пишет новые скиллы по конвенциям репозитория: структура, frontmatter, воркфлоу и примеры кода. CX Codex +1 321установок cost-latency-optimizer Скилл разбирает, куда уходят деньги и время в LLM-приложении, и предлагает кеш, выбор модели, батчинг и сжатие промптов. CX Codex +1 322установок rate-limiting-abuse-protection Скилл добавляет в проект ограничение частоты запросов: политики на маршрут, лимиты по IP и пользователю, скользящее окно и понятные ответы об ошибке. CX Codex +1 319установок load-test-builder Собирает нагрузочные и стресс-тесты на k6, Artillery или autocannon и помогает встроить их в CI как проверку производительности. CX Codex +1 316установок api-test-suite-generator Скилл сканирует определения маршрутов и генерирует тесты API на Jest, Vitest или Supertest. Пригодится, когда эндпоинты уже есть, а тестов к ним нет. CX Codex +1 303установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой