跳到正文
← 博客

OpenSpec 落地使用完整操作手册

· renmk

OpenSpec 是一种用于规范 API 接口定义的标准化格式,旨在提升前后端协作效率、降低沟通成本、确保接口质量。本手册面向开发团队、架构师和技术负责人,系统介绍 OpenSpec 的核心概念、环境搭建、规范定义、工具链使用及最佳实践。通过本手册的学习,读者将能够掌握 OpenSpec 的完整落地流程,从项目初始化到生产环境部署的全链路操作,实现接口规范的自动化管理和持续集成。

第一章:OpenSpec 概述

1.1 什么是 OpenSpec

OpenSpec 是一种开放的 API 规范定义标准,基于 YAML/JSON 格式描述 RESTful API 的接口信息,包括:

  • 接口路径与 HTTP 方法:定义 API 的访问端点
  • 请求参数:Query、Path、Header、Body 等各类参数
  • 响应结构:成功/失败返回的数据格式
  • 数据模型:DTO、VO、Entity 等数据结构的定义
  • 认证授权:API 的安全访问控制
  • 文档说明:接口的功能描述和使用说明

1.2 OpenSpec 的核心价值

价值维度 具体收益
协作效率 前后端基于统一规范并行开发,减少等待和返工
接口质量 通过规范约束减少接口设计缺陷,提升一致性
自动化能力 支持代码生成、Mock 服务、自动化测试等
文档维护 规范即文档,避免文档与代码不同步
生态兼容 与 Swagger、OpenAPI 等主流工具链无缝集成

1.3 适用场景

  • 微服务架构下的 API 治理
  • 前后端分离项目的接口管理
  • 多团队协作的大型项目
  • 需要自动化测试和文档生成的项目
  • API 对外开放和第三方集成场景

第二章:环境准备

2.1 基础环境要求

Plain Text
Node.js >= 16.0.0
npm >= 8.0.0 或 yarn >= 1.22.0
Git >= 2.30.0

2.2 安装 OpenSpec CLI 工具

Bash
# 全局安装 OpenSpec CLI
npm install -g @openspec/cli

# 验证安装
openspec --version

# 查看帮助
openspec --help

2.3 项目初始化

Bash
# 创建新项目目录
mkdir my-api-project
cd my-api-project

# 初始化 OpenSpec 项目
openspec init

# 交互式配置项目信息
# - 项目名称
# - 版本号
# - 描述信息
# - 基础路径
# - 默认响应格式

初始化完成后,项目结构如下:

Plain Text
my-api-project/
├── openspec.yml          # 主配置文件
├── spec/                 # 规范定义目录
│   ├── paths/            # 接口路径定义
│   ├── schemas/          # 数据模型定义
│   ├── parameters/       # 公共参数定义
│   ├── responses/        # 公共响应定义
│   └── security/         # 安全认证定义
├── docs/                 # 生成的文档
├── mocks/                # Mock 数据
├── scripts/              # 工具脚本
└── package.json

2.4 IDE 插件配置

VS Code 用户:

Bash
# 安装 OpenSpec 扩展
# 1. 打开 VS Code
# 2. 进入扩展市场 (Ctrl+Shift+X)
# 3. 搜索 "OpenSpec"
# 4. 安装 "OpenSpec Language Support"

配置 .vscode/settings.json:

JSON
{
  "openspec.validateOnSave": true,
  "openspec.autoFormat": true,
  "openspec.schemaPath": "./openspec.yml",
  "yaml.schemas": {
    "https://openspec.io/schema.json": "*.ospec.yml"
  }
}

第三章:OpenSpec 规范定义

3.1 主配置文件 openspec.yml

YAML
# OpenSpec 主配置文件
openspec: "1.0.0"

info:
  title: 用户管理系统 API
  version: 1.0.0
  description: |
    提供用户注册、登录、信息管理等功能的 RESTful API。
    支持多种认证方式,包括 JWT Token 和 API Key。
  contact:
    name: 技术支持团队
    email: api-support@example.com
    url: https://example.com/support
  license:
    name: MIT
    url: https://opensource.org/licenses/MIT

servers:
  - url: https://api.example.com/v1
    description: 生产环境
  - url: https://staging-api.example.com/v1
    description: 测试环境
  - url: http://localhost:8080/v1
    description: 本地开发环境

# 全局安全配置
security:
  - bearerAuth: []

# 引用其他模块
paths:
  $ref: ./spec/paths/*.yml

components:
  schemas:
    $ref: ./spec/schemas/*.yml
  parameters:
    $ref: ./spec/parameters/*.yml
  responses:
    $ref: ./spec/responses/*.yml
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: JWT Token 认证
    apiKey:
      type: apiKey
      in: header
      name: X-API-Key
      description: API Key 认证

3.2 接口路径定义

创建 spec/paths/users.yml:

YAML
# 用户相关接口定义
/users:
  get:
    summary: 获取用户列表
    description: 分页查询系统中的用户列表,支持多种筛选条件
    operationId: getUserList
    tags:
      - 用户管理
    parameters:
      - $ref: '#/components/parameters/PageNumber'
      - $ref: '#/components/parameters/PageSize'
      - name: keyword
        in: query
        description: 搜索关键词(用户名/邮箱)
        schema:
          type: string
          maxLength: 100
      - name: status
        in: query
        description: 用户状态筛选
        schema:
          type: string
          enum: [active, inactive, suspended]
    responses:
      '200':
        description: 查询成功
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UserListResponse'
      '400':
        $ref: '#/components/responses/BadRequest'
      '401':
        $ref: '#/components/responses/Unauthorized'
      '500':
        $ref: '#/components/responses/InternalError'

  post:
    summary: 创建用户
    description: 注册新用户账号
    operationId: createUser
    tags:
      - 用户管理
    requestBody:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/CreateUserRequest'
    responses:
      '201':
        description: 创建成功
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UserResponse'
      '400':
        $ref: '#/components/responses/BadRequest'
      '409':
        description: 用户已存在
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ErrorResponse'

/users/{userId}:
  get:
    summary: 获取用户详情
    description: 根据用户ID获取详细信息
    operationId: getUserById
    tags:
      - 用户管理
    parameters:
      - name: userId
        in: path
        required: true
        description: 用户唯一标识
        schema:
          type: string
          pattern: '^[a-zA-Z0-9_-]{8,32}$'
    responses:
      '200':
        description: 查询成功
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UserResponse'
      '404':
        $ref: '#/components/responses/NotFound'

  put:
    summary: 更新用户信息
    description: 更新指定用户的全部信息
    operationId: updateUser
    tags:
      - 用户管理
    parameters:
      - name: userId
        in: path
        required: true
        schema:
          type: string
    requestBody:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/UpdateUserRequest'
    responses:
      '200':
        description: 更新成功
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UserResponse'

  delete:
    summary: 删除用户
    description: 软删除指定用户账号
    operationId: deleteUser
    tags:
      - 用户管理
    parameters:
      - name: userId
        in: path
        required: true
        schema:
          type: string
    responses:
      '204':
        description: 删除成功
      '404':
        $ref: '#/components/responses/NotFound'

3.3 数据模型定义

创建 spec/schemas/user.yml:

YAML
# 用户相关数据模型

User:
  type: object
  required:
    - id
    - username
    - email
    - createdAt
  properties:
    id:
      type: string
      description: 用户唯一标识
      example: "usr_12345678"
    username:
      type: string
      description: 用户名
      minLength: 3
      maxLength: 50
      pattern: '^[a-zA-Z0-9_-]+$'
      example: "john_doe"
    email:
      type: string
      format: email
      description: 电子邮箱
      example: "john@example.com"
    phone:
      type: string
      description: 手机号码
      pattern: '^1[3-9]\d{9}$'
      example: "13800138000"
    avatar:
      type: string
      format: uri
      description: 头像URL
      example: "https://cdn.example.com/avatars/usr_12345678.jpg"
    status:
      type: string
      enum: [active, inactive, suspended]
      default: active
      description: 用户状态
    profile:
      $ref: '#/components/schemas/UserProfile'
    createdAt:
      type: string
      format: date-time
      description: 创建时间
    updatedAt:
      type: string
      format: date-time
      description: 更新时间

UserProfile:
  type: object
  properties:
    nickname:
      type: string
      maxLength: 50
      description: 昵称
    gender:
      type: string
      enum: [male, female, other, secret]
      description: 性别
    birthday:
      type: string
      format: date
      description: 生日
    bio:
      type: string
      maxLength: 500
      description: 个人简介
    location:
      type: string
      description: 所在地区

CreateUserRequest:
  type: object
  required:
    - username
    - email
    - password
  properties:
    username:
      type: string
      minLength: 3
      maxLength: 50
    email:
      type: string
      format: email
    password:
      type: string
      format: password
      minLength: 8
      maxLength: 32
      description: 密码必须包含字母、数字和特殊字符
    phone:
      type: string
      pattern: '^1[3-9]\d{9}$'
    profile:
      $ref: '#/components/schemas/UserProfile'

UpdateUserRequest:
  type: object
  properties:
    email:
      type: string
      format: email
    phone:
      type: string
      pattern: '^1[3-9]\d{9}$'
    status:
      type: string
      enum: [active, inactive, suspended]
    profile:
      $ref: '#/components/schemas/UserProfile'

UserResponse:
  type: object
  required:
    - code
    - data
  properties:
    code:
      type: integer
      example: 200
    message:
      type: string
      example: "success"
    data:
      $ref: '#/components/schemas/User'

UserListResponse:
  type: object
  required:
    - code
    - data
  properties:
    code:
      type: integer
      example: 200
    message:
      type: string
      example: "success"
    data:
      type: object
      properties:
        list:
          type: array
          items:
            $ref: '#/components/schemas/User'
        pagination:
          $ref: '#/components/schemas/Pagination'

Pagination:
  type: object
  required:
    - page
    - pageSize
    - total
  properties:
    page:
      type: integer
      minimum: 1
      description: 当前页码
    pageSize:
      type: integer
      minimum: 1
      maximum: 100
      description: 每页数量
    total:
      type: integer
      minimum: 0
      description: 总记录数
    totalPages:
      type: integer
      description: 总页数

ErrorResponse:
  type: object
  required:
    - code
    - message
  properties:
    code:
      type: integer
      description: 错误码
    message:
      type: string
      description: 错误信息
    details:
      type: array
      items:
        type: object
        properties:
          field:
            type: string
            description: 错误字段
          message:
            type: string
            description: 字段错误信息

3.4 公共参数定义

创建 spec/parameters/common.yml:

YAML
# 公共查询参数

PageNumber:
  name: page
  in: query
  description: 页码,从1开始
  schema:
    type: integer
    minimum: 1
    default: 1

PageSize:
  name: pageSize
  in: query
  description: 每页数量
  schema:
    type: integer
    minimum: 1
    maximum: 100
    default: 20

SortField:
  name: sortBy
  in: query
  description: 排序字段
  schema:
    type: string

SortOrder:
  name: order
  in: query
  description: 排序方式
  schema:
    type: string
    enum: [asc, desc]
    default: desc

Language:
  name: Accept-Language
  in: header
  description: 语言偏好
  schema:
    type: string
    default: zh-CN
    enum: [zh-CN, en-US, ja-JP]

RequestId:
  name: X-Request-ID
  in: header
  description: 请求追踪ID
  schema:
    type: string
    format: uuid

3.5 公共响应定义

创建 spec/responses/common.yml:

YAML
# 公共响应定义

BadRequest:
  description: 请求参数错误
  content:
    application/json:
      schema:
        $ref: '#/components/schemas/ErrorResponse'
      example:
        code: 400
        message: "请求参数验证失败"
        details:
          - field: "email"
            message: "邮箱格式不正确"

Unauthorized:
  description: 未授权访问
  content:
    application/json:
      schema:
        $ref: '#/components/schemas/ErrorResponse'
      example:
        code: 401
        message: "认证失败,请重新登录"

Forbidden:
  description: 禁止访问
  content:
    application/json:
      schema:
        $ref: '#/components/schemas/ErrorResponse'
      example:
        code: 403
        message: "没有权限执行此操作"

NotFound:
  description: 资源不存在
  content:
    application/json:
      schema:
        $ref: '#/components/schemas/ErrorResponse'
      example:
        code: 404
        message: "请求的资源不存在"

InternalError:
  description: 服务器内部错误
  content:
    application/json:
      schema:
        $ref: '#/components/schemas/ErrorResponse'
      example:
        code: 500
        message: "服务器内部错误,请稍后重试"

第四章:工具链使用

4.1 规范验证

Bash
# 验证规范文件语法
openspec validate

# 验证指定文件
openspec validate ./spec/paths/users.yml

# 详细验证报告
openspec validate --verbose

# 输出 JSON 格式报告
openspec validate --format json --output validation-report.json

4.2 文档生成

Bash
# 生成 HTML 文档
openspec generate docs --format html --output ./docs

# 生成 Markdown 文档
openspec generate docs --format markdown --output ./docs/api.md

# 生成 PDF 文档(需安装额外依赖)
openspec generate docs --format pdf --output ./docs/api.pdf

# 启动本地文档服务器
openspec serve --port 3000

4.3 代码生成

生成服务端代码:

Bash
# 生成 Spring Boot 项目
openspec generate server --framework spring --output ./server

# 生成 Express.js 项目
openspec generate server --framework express --output ./server

# 生成 FastAPI 项目
openspec generate server --framework fastapi --output ./server

生成客户端代码:

Bash
# 生成 TypeScript 客户端
openspec generate client --language typescript --output ./client/ts

# 生成 JavaScript 客户端
openspec generate client --language javascript --output ./client/js

# 生成 Python 客户端
openspec generate client --language python --output ./client/python

# 生成 Java 客户端
openspec generate client --language java --output ./client/java

生成类型定义:

Bash
# 生成 TypeScript 类型
openspec generate types --language typescript --output ./types

# 生成 Go 结构体
openspec generate types --language go --output ./types

4.4 Mock 服务

Bash
# 启动 Mock 服务器
openspec mock --port 8080

# 使用自定义 Mock 数据
openspec mock --data ./mocks --port 8080

# 延迟响应模拟
openspec mock --delay 500 --port 8080

# 指定错误率模拟异常情况
openspec mock --error-rate 0.1 --port 8080

4.5 测试生成

Bash
# 生成接口测试用例
openspec generate tests --framework jest --output ./tests

# 生成 Postman 集合
openspec generate collection --format postman --output ./tests/api.postman_collection.json

# 生成 Newman 测试脚本
openspec generate tests --framework newman --output ./tests/newman

第五章:CI/CD 集成

5.1 GitHub Actions 集成

创建 .github/workflows/openspec.yml:

YAML
name: OpenSpec CI

on:
  push:
    branches: [main, develop]
    paths:
      - 'spec/**'
      - 'openspec.yml'
  pull_request:
    branches: [main]
    paths:
      - 'spec/**'
      - 'openspec.yml'

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18'
          cache: 'npm'

      - name: Install OpenSpec CLI
        run: npm install -g @openspec/cli

      - name: Validate OpenSpec
        run: openspec validate --verbose

      - name: Upload validation report
        uses: actions/upload-artifact@v4
        if: failure()
        with:
          name: validation-report
          path: validation-report.json

  generate-docs:
    needs: validate
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'
    steps:
      - uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18'
          cache: 'npm'

      - name: Install OpenSpec CLI
        run: npm install -g @openspec/cli

      - name: Generate Documentation
        run: openspec generate docs --format html --output ./docs

      - name: Deploy to GitHub Pages
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./docs

  generate-client:
    needs: validate
    runs-on: ubuntu-latest
    strategy:
      matrix:
        language: [typescript, javascript, python]
    steps:
      - uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18'

      - name: Install OpenSpec CLI
        run: npm install -g @openspec/cli

      - name: Generate Client SDK
        run: |
          openspec generate client \
            --language ${{ matrix.language }} \
            --output ./sdks/${{ matrix.language }}

      - name: Package SDK
        run: |
          cd ./sdks/${{ matrix.language }}
          zip -r ../${{ matrix.language }}-sdk.zip .

      - name: Upload SDK Artifact
        uses: actions/upload-artifact@v4
        with:
          name: ${{ matrix.language }}-sdk
          path: ./sdks/${{ matrix.language }}-sdk.zip

5.2 GitLab CI 集成

创建 .gitlab-ci.yml:

YAML
stages:
  - validate
  - generate
  - deploy

variables:
  NODE_VERSION: "18"

validate_openspec:
  stage: validate
  image: node:${NODE_VERSION}
  before_script:
    - npm install -g @openspec/cli
  script:
    - openspec validate --verbose
  artifacts:
    when: on_failure
    paths:
      - validation-report.json
    expire_in: 1 week
  only:
    changes:
      - spec/**/*
      - openspec.yml

generate_docs:
  stage: generate
  image: node:${NODE_VERSION}
  dependencies:
    - validate_openspec
  before_script:
    - npm install -g @openspec/cli
  script:
    - openspec generate docs --format html --output public
  artifacts:
    paths:
      - public
    expire_in: 1 week
  only:
    - main

pages:
  stage: deploy
  dependencies:
    - generate_docs
  script:
    - echo "Deploying to GitLab Pages"
  artifacts:
    paths:
      - public
  only:
    - main

5.3 Jenkins 集成

创建 Jenkinsfile:

GROOVY
pipeline {
    agent any

    tools {
        nodejs 'NodeJS-18'
    }

    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }

        stage('Install Dependencies') {
            steps {
                sh 'npm install -g @openspec/cli'
            }
        }

        stage('Validate') {
            steps {
                sh 'openspec validate --verbose'
            }
        }

        stage('Generate Artifacts') {
            parallel {
                stage('Documentation') {
                    steps {
                        sh 'openspec generate docs --format html --output ./docs'
                        publishHTML([
                            allowMissing: false,
                            alwaysLinkToLastBuild: true,
                            keepAll: true,
                            reportDir: 'docs',
                            reportFiles: 'index.html',
                            reportName: 'API Documentation'
                        ])
                    }
                }
                stage('Client SDKs') {
                    steps {
                        sh '''
                            mkdir -p sdks
                            openspec generate client --language typescript --output ./sdks/typescript
                            openspec generate client --language python --output ./sdks/python
                            cd sdks && zip -r sdks.zip .
                        '''
                        archiveArtifacts artifacts: 'sdks/sdks.zip', fingerprint: true
                    }
                }
            }
        }

        stage('Deploy') {
            when {
                branch 'main'
            }
            steps {
                sh 'echo "Deploying to production..."'
                // 添加实际部署步骤
            }
        }
    }

    post {
        always {
            cleanWs()
        }
        failure {
            emailext (
                subject: "OpenSpec Build Failed: \${env.JOB_NAME} - \${env.BUILD_NUMBER}",
                body: "Build failed. Check console output at \${env.BUILD_URL}",
                to: "\${env.CHANGE_AUTHOR_EMAIL}"
            )
        }
    }
}

第六章:最佳实践

6.1 版本管理策略

YAML
# 使用语义化版本控制
info:
  version: 1.2.3  # 主版本.次版本.修订号

# 版本升级规则:
# - 主版本:不兼容的 API 变更
# - 次版本:向下兼容的功能新增
# - 修订号:向下兼容的问题修复

API 版本控制方案:

  1. URL 路径版本(推荐)

    Plain Text
    /v1/users
    /v2/users
  2. 请求头版本

    Plain Text
    Accept: application/vnd.api+json;version=1
    X-API-Version: 2
  3. 查询参数版本

    Plain Text
    /users?api-version=1.0

6.2 命名规范

元素类型 命名规范 示例
接口路径 小写、复数、连字符分隔 /user-profiles, /order-items
参数名 驼峰命名 userId, createdAt
模型名 PascalCase UserProfile, OrderItem
枚举值 大写下划线分隔 ACTIVE, IN_PROGRESS
操作ID 驼峰命名 getUserById, createOrder

6.3 错误处理规范

YAML
# 统一的错误响应结构
ErrorResponse:
  type: object
  required:
    - code
    - message
    - requestId
    - timestamp
  properties:
    code:
      type: integer
      description: HTTP 状态码
    message:
      type: string
      description: 用户友好的错误信息
    errorCode:
      type: string
      description: 业务错误码
      example: "USER_NOT_FOUND"
    details:
      type: array
      description: 详细错误信息
      items:
        type: object
        properties:
          field:
            type: string
          message:
            type: string
    requestId:
      type: string
      description: 请求追踪ID
    timestamp:
      type: string
      format: date-time
      description: 错误发生时间
    path:
      type: string
      description: 请求路径

标准 HTTP 状态码使用:

状态码 使用场景
200 GET/PUT/PATCH 请求成功
201 POST 创建成功
204 DELETE 删除成功
400 请求参数错误
401 未认证
403 无权限
404 资源不存在
409 资源冲突
422 业务逻辑验证失败
429 请求过于频繁
500 服务器内部错误

6.4 安全规范

YAML
# 安全认证配置
components:
  securitySchemes:
    # JWT Bearer Token
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: |
        使用 JWT Token 进行认证。
        在请求头中添加:Authorization: Bearer <token>

    # API Key
    apiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
      description: 服务端间通信使用的 API Key

    # OAuth2
    oauth2:
      type: oauth2
      flows:
        authorizationCode:
          authorizationUrl: https://auth.example.com/oauth/authorize
          tokenUrl: https://auth.example.com/oauth/token
          scopes:
            read: 读取权限
            write: 写入权限
            admin: 管理权限

security:
  - bearerAuth: []

paths:
  /public/info:
    get:
      security: []  # 公开接口,无需认证

  /admin/users:
    get:
      security:
        - bearerAuth: []
          oauth2: [admin]  # 需要管理员权限

6.5 性能优化

YAML
# 分页查询优化
parameters:
  - name: page
    in: query
    schema:
      type: integer
      minimum: 1
      default: 1

  - name: pageSize
    in: query
    schema:
      type: integer
      minimum: 1
      maximum: 100  # 限制最大数量
      default: 20

  - name: fields
    in: query
    description: 指定返回字段,减少数据传输
    schema:
      type: array
      items:
        type: string
      example: ["id", "username", "email"]

# 缓存控制
responses:
  '200':
    headers:
      Cache-Control:
        schema:
          type: string
          example: "max-age=3600"
      ETag:
        schema:
          type: string

6.6 团队协作规范

分支管理策略:

Plain Text
main          # 生产环境分支
├── develop   # 开发分支
├── feature/user-api    # 功能分支
├── feature/order-api   # 功能分支
└── hotfix/security     # 紧急修复分支

代码审查清单:

  • 规范文件语法正确,能通过验证
  • 接口命名符合 RESTful 规范
  • 数据模型包含完整的字段说明和示例
  • 错误响应定义完整
  • 安全认证配置正确
  • 版本号已更新(如需要)
  • 文档说明清晰完整

第七章:常见问题排查

7.1 验证错误处理

错误类型 可能原因 解决方案
YAML 语法错误 缩进不正确、特殊字符未转义 使用 YAML 验证工具检查
$ref 引用错误 路径错误或目标不存在 检查引用路径和文件是否存在
类型不匹配 字段类型与实际值不符 检查 schema 定义和示例数据
必填字段缺失 required 字段未提供 补充缺失的必填字段
循环引用 模型间循环 $ref 重构模型结构,消除循环

7.2 调试技巧

Bash
# 启用详细日志
DEBUG=openspec:* openspec validate

# 分步验证
openspec validate --step parse
openspec validate --step resolve
openspec validate --step semantic

# 导出完整解析结果
openspec export --format json --output full-spec.json

7.3 性能优化

Bash
# 大型项目优化
openspec validate --cache --parallel

# 增量验证(只验证变更文件)
openspec validate --diff --base-branch main

# 排除特定路径
openspec validate --exclude "**/deprecated/**"

第八章:扩展与定制

8.1 自定义插件开发

JavaScript
// plugins/custom-validator.js
module.exports = {
  name: 'custom-validator',
  version: '1.0.0',

  validate(spec) {
    const errors = [];

    // 自定义验证规则:检查所有接口必须有 tags
    for (const [path, methods] of Object.entries(spec.paths)) {
      for (const [method, operation] of Object.entries(methods)) {
        if (!operation.tags || operation.tags.length === 0) {
          errors.push({
            path: `paths.${path}.${method}`,
            message: 'Operation must have at least one tag'
          });
        }
      }
    }

    return errors;
  }
};

配置使用插件:

YAML
# openspec.yml
plugins:
  - ./plugins/custom-validator.js
  - @openspec/plugin-security-audit

8.2 自定义模板

Bash
# 创建自定义模板目录
mkdir -p templates/server/spring

# 编写模板文件
templates/server/spring/
├── controller.java.hbs
├── service.java.hbs
├── dto.java.hbs
└── mapper.xml.hbs

# 使用自定义模板生成代码
openspec generate server --template ./templates/server/spring --output ./server

第九章:附录

9.1 完整示例项目结构

Plain Text
openspec-demo/
├── openspec.yml                 # 主配置文件
├── package.json
├── README.md
├── .gitignore
├── .openspecrc                  # CLI 配置文件
├── .github/
│   └── workflows/
│       └── openspec.yml         # CI/CD 配置
├── spec/
│   ├── paths/
│   │   ├── users.yml
│   │   ├── orders.yml
│   │   └── auth.yml
│   ├── schemas/
│   │   ├── user.yml
│   │   ├── order.yml
│   │   └── common.yml
│   ├── parameters/
│   │   └── common.yml
│   ├── responses/
│   │   └── common.yml
│   └── security/
│       └── oauth2.yml
├── docs/                        # 生成的文档
├── mocks/                       # Mock 数据
├── scripts/
│   ├── validate.sh
│   ├── generate.sh
│   └── deploy.sh
└── sdks/                        # 生成的 SDK
    ├── typescript/
    ├── python/
    └── java/

9.2 常用命令速查表

命令 说明
openspec init 初始化项目
openspec validate 验证规范
openspec serve 启动文档服务器
openspec mock 启动 Mock 服务
openspec generate docs 生成文档
openspec generate server 生成服务端代码
openspec generate client 生成客户端 SDK
openspec generate types 生成类型定义
openspec generate tests 生成测试用例
openspec export 导出规范文件
openspec diff 比较版本差异
openspec merge 合并多个规范

9.3 相关资源


结语

OpenSpec 作为现代化的 API 规范管理工具,能够显著提升团队的开发效率和接口质量。通过本手册的学习,您已经掌握了 OpenSpec 从环境搭建到生产部署的完整流程。

在实际落地过程中,建议:

  1. 从小范围试点开始,选择 1-2 个核心模块先行实践
  2. 建立团队规范,统一命名、版本、安全等标准
  3. 集成 CI/CD 流程,实现自动化的验证和文档发布
  4. 持续迭代优化,根据团队反馈调整使用方式
  5. 培养规范意识,让接口设计成为团队的共同责任

祝您的 OpenSpec 落地之旅顺利!