openapi swagger skills

简介: 本技能专为生成、审查与优化OpenAPI/Swagger文档而设计,遵循API优先原则,支持OpenAPI 3.1(默认)、3.0.x及Swagger 2.0。涵盖路径设计、HTTP语义、参数/响应/安全定义、错误模型、分页、异步任务等18项规范,确保文档准确、一致、可读、工具友好,适用于设计评审、文档生成、契约对齐与测试等场景。(239字)

openapi-swagger-doc-skill

Purpose

This skill guides the agent to create, review, and improve OpenAPI / Swagger documentation that is accurate, consistent, readable, tool-friendly, and aligned with API design best practices.

The agent should produce OpenAPI documents that can be used for API design review, Swagger UI / Redoc documentation, frontend-backend contract alignment, mock server generation, client SDK generation, API testing, and contract testing.

Prefer OpenAPI 3.1 unless the user’s project or tooling explicitly requires OpenAPI 3.0.x or Swagger 2.0.


When to Use This Skill

Use this skill when the user asks to:

  • Write OpenAPI / Swagger documentation
  • Convert API descriptions into OpenAPI YAML or JSON
  • Review existing Swagger / OpenAPI files
  • Design RESTful API contracts
  • Generate API docs from controller or service descriptions
  • Standardize API request and response formats
  • Improve API documentation quality
  • Add examples, schemas, error codes, parameters, or authentication definitions

Core Principles

1. Prefer API-first / Design-first

Before writing implementation details, clarify the API contract:

  • What resource is exposed
  • Who calls the API
  • What business action it represents
  • What request parameters are required
  • What response body is returned
  • What errors can happen
  • What authentication is required

Do not blindly mirror backend method names or database table names.

Good API documentation should describe the external contract, not the internal implementation.

2. Use OpenAPI 3.x Structure

The generated document should normally include:

openapi: 3.1.0
info:
  title: Example API
  version: 1.0.0
  description: API description
servers:
  - url: https://api.example.com
    description: Production
tags: []
paths: {
   }
components:
  schemas: {
   }
  parameters: {
   }
  responses: {
   }
  securitySchemes: {
   }
security: []
`

Use YAML by default because it is easier for humans to read and maintain.


Writing Rules

1. Path Design

Use resource-oriented paths.

Prefer:

/users/{
   userId}
/orders/{
   orderId}/items
/model-evaluation-tasks/{
   taskId}

Avoid:

/getUser
/createOrder
/queryTaskInfo
/doEvaluation

Rules:

  • Use nouns, not verbs
  • Use lowercase path segments
  • Use hyphen-case for multi-word resources
  • Use plural resource names where appropriate
  • Use path parameters only for resource identity
  • Use query parameters for filtering, pagination, sorting, and optional search conditions

Example:

GET /model-evaluation-tasks?status=RUNNING&page=1&pageSize=20

2. HTTP Method Semantics

Use HTTP methods consistently:

  • GET: read resource, no side effects
  • POST: create resource or trigger non-idempotent action
  • PUT: replace entire resource
  • PATCH: partially update resource
  • DELETE: delete resource

Do not use GET for operations that change server state.

3. Operation Metadata

Every operation should include:

  • tags
  • summary
  • description
  • operationId
  • parameters, if needed
  • requestBody, if needed
  • responses
  • security, if different from global security

Example:

operationId: createModelEvaluationTask
summary: Create a model evaluation task
description: Creates an asynchronous task to evaluate a large model against a dataset.

Rules:

  • summary should be short
  • description should explain business behavior and important constraints
  • operationId should be stable, unique, and code-generation friendly
  • Use lowerCamelCase for operationId

4. Parameters

Use parameter locations correctly:

  • path: resource identity
  • query: filtering, pagination, sorting
  • header: request metadata, tracing, auth-related metadata
  • cookie: only when cookie-based API behavior is required

Every path parameter must be marked as required:

parameters:
  - name: taskId
    in: path
    required: true
    description: Unique ID of the evaluation task.
    schema:
      type: string

For pagination, prefer consistent names:

page:
  type: integer
  minimum: 1
  default: 1

pageSize:
  type: integer
  minimum: 1
  maximum: 100
  default: 20

5. Request Body

Use requestBody for JSON payloads in POST, PUT, and PATCH.

Example:

requestBody:
  required: true
  content:
    application/json:
      schema:
        $ref: '#/components/schemas/CreateEvaluationTaskRequest'
      examples:
        basic:
          summary: Basic request
          value:
            modelId: "model-001"
            datasetId: "dataset-001"

Rules:

  • Always declare content type
  • Prefer schema references under components.schemas
  • Provide examples for important APIs
  • Mark required fields explicitly inside the schema

6. Responses

Every operation must define responses. At minimum, include one successful response and common error responses.

Example:

responses:
  '201':
    description: Evaluation task created successfully.
    content:
      application/json:
        schema:
          $ref: '#/components/schemas/CreateEvaluationTaskResponse'
  '400':
    $ref: '#/components/responses/BadRequest'
  '401':
    $ref: '#/components/responses/Unauthorized'
  '500':
    $ref: '#/components/responses/InternalServerError'

Rules:

  • Do not only write 200
  • Use accurate HTTP status codes
  • Include error responses
  • Include response examples where useful
  • Use reusable common responses under components.responses

Recommended status codes:

  • 200: successful query or update
  • 201: resource created
  • 202: accepted async task
  • 204: successful delete or no response body
  • 400: invalid request
  • 401: not authenticated
  • 403: no permission
  • 404: resource not found
  • 409: conflict
  • 422: semantic validation failed
  • 429: rate limited
  • 500: server error

For asynchronous APIs, prefer:

'202':
  description: Task accepted and will be processed asynchronously.

7. Schemas

Define reusable schemas under components.schemas.

Example:

components:
  schemas:
    CreateEvaluationTaskRequest:
      type: object
      required:
        - modelId
        - datasetId
      properties:
        modelId:
          type: string
          description: ID of the model to evaluate.
          example: model-001
        datasetId:
          type: string
          description: ID of the dataset used for evaluation.
          example: dataset-001

Rules:

  • Use meaningful schema names
  • Use PascalCase for schema names
  • Use lowerCamelCase for property names unless the API already uses another convention
  • Add description for non-obvious fields
  • Add example for important fields
  • Use enum for fixed values
  • Use format for known formats such as date-time, uuid, int64
  • Avoid vague object fields without structure
  • Avoid overusing additionalProperties: true

8. Error Model

Define a standard error response.

Example:

ErrorResponse:
  type: object
  required:
    - code
    - message
    - traceId
  properties:
    code:
      type: string
      description: Business error code.
      example: INVALID_ARGUMENT
    message:
      type: string
      description: Human-readable error message.
      example: The datasetId field is required.
    traceId:
      type: string
      description: Trace ID for troubleshooting.
      example: 9f8c7a6b5d4e3f21
    details:
      type: array
      description: Additional validation errors.
      items:
        type: object
        properties:
          field:
            type: string
            example: datasetId
          reason:
            type: string
            example: must not be empty

Common reusable responses:

responses:
  BadRequest:
    description: Invalid request.
    content:
      application/json:
        schema:
          $ref: '#/components/schemas/ErrorResponse'
  Unauthorized:
    description: Authentication is required.
    content:
      application/json:
        schema:
          $ref: '#/components/schemas/ErrorResponse'
  Forbidden:
    description: Permission denied.
    content:
      application/json:
        schema:
          $ref: '#/components/schemas/ErrorResponse'
  NotFound:
    description: Resource not found.
    content:
      application/json:
        schema:
          $ref: '#/components/schemas/ErrorResponse'
  InternalServerError:
    description: Internal server error.
    content:
      application/json:
        schema:
          $ref: '#/components/schemas/ErrorResponse'

9. Authentication and Security

Define security schemes under components.securitySchemes.

Bearer token example:

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

security:
  - bearerAuth: []

API key example:

components:
  securitySchemes:
    apiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key

Rules:

  • Do not describe authentication only in prose
  • Use OpenAPI security schemes
  • Define global security if most APIs require authentication
  • Override operation-level security only when needed
  • Mark public endpoints explicitly when necessary:
security: []

10. Examples

For important APIs, provide request and response examples.

Examples should be realistic and consistent with the schema.

Bad:

example:
  id: string
  name: string

Good:

example:
  id: "task-20260513-001"
  status: "RUNNING"
  createdAt: "2026-05-13T10:30:00Z"

Rules:

  • Use realistic IDs, timestamps, and values
  • Include success examples
  • Include error examples for complex validation
  • Keep examples synchronized with schemas

11. Naming Conventions

Recommended conventions:

  • Path: kebab-case, for example /model-evaluation-tasks
  • Path parameter: lowerCamelCase, for example {taskId}
  • Query parameter: lowerCamelCase, for example pageSize
  • JSON field: lowerCamelCase, for example createdAt
  • Schema name: PascalCase, for example EvaluationTask
  • Operation ID: lowerCamelCase, for example createEvaluationTask
  • Tag: human readable, for example Model Evaluation

12. Pagination

Use a consistent pagination response.

Example:

PageResult:
  type: object
  required:
    - page
    - pageSize
    - total
    - items
  properties:
    page:
      type: integer
      example: 1
    pageSize:
      type: integer
      example: 20
    total:
      type: integer
      format: int64
      example: 128
    items:
      type: array
      items: {
   }

For specific resources, define concrete page schemas:

EvaluationTaskPage:
  allOf:
    - $ref: '#/components/schemas/PageResult'
    - type: object
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/EvaluationTask'

13. Sorting and Filtering

For list APIs, document all supported filters.

Example:

parameters:
  - name: status
    in: query
    required: false
    description: Filter tasks by status.
    schema:
      $ref: '#/components/schemas/EvaluationTaskStatus'
  - name: sort
    in: query
    required: false
    description: Sort expression. Prefix with '-' for descending order.
    schema:
      type: string
      example: "-createdAt"

Avoid undocumented magic query parameters.

14. Async Task APIs

For asynchronous tasks, document the lifecycle clearly.

Recommended endpoints:

POST /evaluation-tasks
GET /evaluation-tasks/{taskId}
GET /evaluation-tasks/{taskId}/results
POST /evaluation-tasks/{taskId}/cancel

Recommended status enum:

EvaluationTaskStatus:
  type: string
  enum:
    - PENDING
    - RUNNING
    - SUCCEEDED
    - FAILED
    - CANCELED

For task creation, use 202 Accepted if processing starts asynchronously.

15. File Upload APIs

Use multipart/form-data.

Example:

requestBody:
  required: true
  content:
    multipart/form-data:
      schema:
        type: object
        required:
          - file
        properties:
          file:
            type: string
            format: binary
          description:
            type: string

16. Streaming APIs

For Server-Sent Events:

responses:
  '200':
    description: Streaming response using Server-Sent Events.
    content:
      text/event-stream:
        schema:
          type: string
          description: SSE event stream.

For plain streaming text:

content:
  text/plain:
    schema:
      type: string

Clearly document:

  • Stream content type
  • Event format
  • End condition
  • Error behavior
  • Whether partial output is possible

17. Versioning

Prefer versioning through URL or header depending on project standard.

Common URL versioning:

servers:
  - url: https://api.example.com/v1

Rules:

  • Do not mix multiple versioning styles casually
  • Keep info.version for document version
  • Keep API version strategy explicit

18. Validation Checklist

Before finalizing OpenAPI output, verify:

  • openapi, info, servers, paths, and components exist
  • Every operation has summary, operationId, and responses
  • Every path parameter is declared and required
  • Every request body has a schema
  • Every response has a meaningful description
  • Common errors are documented
  • Schemas use correct required fields
  • Enums are explicitly defined
  • Examples match schema definitions
  • Authentication is defined with securitySchemes
  • Reusable objects are placed in components
  • Names are consistent
  • No internal implementation details are leaked
  • No database-only field names are exposed unless they are part of the public contract
  • The document can be validated by OpenAPI tooling

Output Style

When creating OpenAPI documentation, output in this order:

  1. Brief explanation of assumptions
  2. Complete OpenAPI YAML
  3. Notes or improvement suggestions, if needed

When reviewing OpenAPI documentation, output in this order:

  1. Major issues
  2. Contract consistency issues
  3. Schema and response problems
  4. Naming and style suggestions
  5. Corrected YAML snippets

Default OpenAPI Template

Use this as a starting point when the user has not provided an existing file.

openapi: 3.1.0

info:
  title: Example API
  version: 1.0.0
  description: Example OpenAPI documentation.

servers:
  - url: https://api.example.com/v1
    description: Production server

tags:
  - name: Example
    description: Example APIs

paths:
  /examples:
    get:
      tags:
        - Example
      operationId: listExamples
      summary: List examples
      description: Returns a paginated list of examples.
      parameters:
        - name: page
          in: query
          required: false
          description: Page number, starting from 1.
          schema:
            type: integer
            minimum: 1
            default: 1
        - name: pageSize
          in: query
          required: false
          description: Number of records per page.
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 20
      responses:
        '200':
          description: Examples returned successfully.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ExamplePage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '500':
          $ref: '#/components/responses/InternalServerError'

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

  schemas:
    Example:
      type: object
      required:
        - id
        - name
        - createdAt
      properties:
        id:
          type: string
          description: Unique ID of the example.
          example: example-001
        name:
          type: string
          description: Name of the example.
          example: Demo example
        createdAt:
          type: string
          format: date-time
          description: Creation time.
          example: '2026-05-13T10:30:00Z'

    ExamplePage:
      type: object
      required:
        - page
        - pageSize
        - total
        - items
      properties:
        page:
          type: integer
          example: 1
        pageSize:
          type: integer
          example: 20
        total:
          type: integer
          format: int64
          example: 100
        items:
          type: array
          items:
            $ref: '#/components/schemas/Example'

    ErrorResponse:
      type: object
      required:
        - code
        - message
        - traceId
      properties:
        code:
          type: string
          example: INVALID_ARGUMENT
        message:
          type: string
          example: Invalid request parameter.
        traceId:
          type: string
          example: 9f8c7a6b5d4e3f21

  responses:
    BadRequest:
      description: Invalid request.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Unauthorized:
      description: Authentication is required.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Forbidden:
      description: Permission denied.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    NotFound:
      description: Resource not found.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    InternalServerError:
      description: Internal server error.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'

security:
  - bearerAuth: []

Common Anti-patterns

Avoid these patterns:

  • Only documenting happy-path 200 responses
  • Missing error response model
  • No examples
  • All schemas defined inline
  • Overusing type: object without fields
  • Exposing database table structure directly
  • Using vague field names like data, info, obj without schema
  • Inconsistent status codes
  • Using GET for state-changing operations
  • Duplicating the same parameter definitions everywhere
  • Missing authentication definitions
  • Inconsistent naming style
  • Operation IDs generated from backend method names without cleanup

Agent Behavior Rules

When information is missing, make reasonable assumptions and state them clearly.

Do not ask excessive clarification questions. If the user gives partial API information, generate a best-effort OpenAPI draft and mark uncertain parts as assumptions or TODO comments.

When the user provides Java Controller code, infer:

  • Path from class-level and method-level mappings
  • HTTP method from mapping annotation
  • Request parameters from method arguments
  • Request body from DTOs
  • Response schema from return type
  • Tags from controller name
  • Operation summaries from method names and comments

When the user provides database tables only, do not directly expose table fields as API fields. First infer the business resource model.

When generating documentation for Chinese development teams, field descriptions may be in Chinese, but schema names, operation IDs, and paths should normally remain English unless the project standard says otherwise.

相关文章
|
2月前
|
机器学习/深度学习 人工智能 开发者
AI 编程时代来了!Karpathy 出品「避坑指南」一夜爆火
AI编程时代来临,Karpathy指出四大通病:错误假设、代码臃肿、误改无关代码、缺乏验证标准。开发者Forrest Chang据此推出开源《CLAUDE.md》指南,通过“思考优先、简单优先、精准改动、目标驱动”四原则,让Claude Code更可靠、高效、可控。(239字)
509 1
|
1月前
|
存储 SQL 人工智能
AI Coding Agent 时代:代码越便宜,约束越贵
AI时代,代码生成成本骤降,但让代码长期可信的工程约束却愈发昂贵。本文通过对比实验揭示:清晰的架构、显式契约与可执行规则,才是引导AI生成高质量代码的关键护栏。
227 0
AI Coding Agent 时代:代码越便宜,约束越贵
|
人工智能 自然语言处理 IDE
通义灵码使用指南
一款不用充钱也能让你变强的插件 通义灵码(TONGYI Lingma),可以称之为中国copilot 的平替品。我们一起看看如何使用安装,功能介绍,常用问题,客户测评等。
10489 12
通义灵码使用指南
|
2天前
|
弹性计算 监控 Java
Maven 并行构建配置:-T 4C 提速 4 倍实战
本文深入讲解了 Maven 并行构建的核心原理和实战技巧,包含 -T 参数详解、模块并行化改造、性能监控与分析等企业级最佳实践。通过真实案例展示了如何将多模块项目的构建时间从 45 分钟缩短到 11 分钟(提升 4.1 倍),提供完整的性能测试脚本和优化检查清单。掌握这些技能,你将能够充分利用多核 CPU 加速 Maven 构建。适合 Java 开发者、架构师、DevOps 工程师阅读。
|
2天前
|
JSON 人工智能 测试技术
我如何用Skills+Postman,让接口测试用例自动生成、自动维护,半年零手工更新
本文揭秘如何用Postman+大模型Skills实现接口测试用例“零手工维护”:通过自动感知OpenAPI变更、智能生成并应用Collection补丁、Git化管理+CI闭环验证,6个月未手动增删改用例。核心不是生成用例,而是让用例随代码自动同步。
|
2天前
|
监控 API Windows
WGCLOUD v3.6.8 正式更新
WGCLOUD v3.6.8发布:修复CPU/内存等指标偶现为0、大屏离线数据不显示等Bug;新增Windows系统服务列表及开放API;优化告警脚本执行与SNMP设备运行时间兼容性。升级方式详见官方图示。
|
2天前
|
存储 人工智能 安全
阿里云服务器经济型e实例2核2G、2核4G、4核8G等配置解析:实例性能、适用场景与活动价格参考
阿里云经济型e实例是面向个人开发者、学生及小微企业的入门级云服务器,2核2G3M带宽仅99元/年,热门配置享3.9折起优惠。产品采用Intel Xeon处理器,支持ESSD Entry云盘,具备企业级SLA与安全标准,国内32个可用区广泛售卖。适用于AI智能体轻载部署、个人学习测试、中小型网站搭建、开发测试环境及轻量级企业应用等场景。
|
2天前
|
人工智能 数据可视化 测试技术
【教程】阿里云轻量云服务器一键配置OpenClaw
如果你还没有部署自己的 OpenClaw,还可以通过购买腾讯的轻量云服务器,一键秒级部署指南一键秒级部署指南,一键即可在几秒内完成部署。
254 9
|
1月前
|
人工智能 IDE JavaScript
通义灵码深度评测-企业内部使用实战
通义灵码深度评测-企业内部使用实战 ,根据企业内部使用实战,建设了微信公众号、视频号、csdn专栏,持续更新了通义灵码企业级实践教程,从入门->精通,从基本功能->高阶功能全面详尽的实战,持续更新中
342 0