> ## Documentation Index
> Fetch the complete documentation index at: https://adminroletesting-justin-client-exports.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# OpenAPI 设置

> 从 OpenAPI 规范文件生成交互式 API 文档，自动创建端点页面、请求构建器和导航结构。

OpenAPI 是用于描述 API 的规范。Mintlify 支持 OpenAPI 3.0 和 3.1 文档，用于生成交互式 API 文档并保持其始终最新。

<div id="add-an-openapi-specification-file">
  ## 添加 OpenAPI 规范文件
</div>

要使用 OpenAPI 为你的端点撰写文档，你需要一个或多个有效的 OpenAPI 规范文件，格式为 JSON 或 YAML，并且遵循 [OpenAPI 3.0 或 3.1 规范](https://swagger.io/specification/)。

将 OpenAPI 规范添加到你的文档存储库中，或将其托管在线，以便你可以通过 URL 访问这些规范。存储在存储库中的规范会在你的文档域名上按照其路径[提供为可下载文件](/zh/create/files)。例如，`https://your-domain/docs/openapi.json`。

在 `docs.json` 的 `navigation` 配置中引用任意数量的 OpenAPI 规范，以为你的 API 端点创建页面。每个规范文件都会生成自己的一组端点。

<CodeGroup>
  ```json Single specification theme={null}
  "navigation": {
    "tabs": [
      {
        "tab": "API Reference",
        "openapi": "openapi.json"
      }
    ]
  }
  ```

  ```json Multiple specifications theme={null}
  "navigation": {
    "tabs": [
      {
        "tab": "API Reference",
        "openapi": [
          "openapi/v1.json",
          "openapi/v2.json"
        ]
      }
    ]
  }
  ```
</CodeGroup>

<Note>
  Mintlify 仅支持在单个 OpenAPI 文档内使用 `$ref` 进行**内部引用**，不支持外部引用。
</Note>

<div id="describe-your-api">
  ### 描述你的 API
</div>

我们推荐以下资源，帮助你学习并编写 OpenAPI 规范。

* [Swagger 的 OpenAPI 指南](https://swagger.io/docs/specification/v3_0/basic-structure/)，用于学习 OpenAPI 语法。
* [OpenAPI 规范的 Markdown 源文件](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/)，用于查阅最新版 OpenAPI 规范的详细信息。
* [Swagger Editor](https://editor.swagger.io/)，用于编辑、验证和调试你的 OpenAPI 文档。
* [Mint CLI](https://www.npmjs.com/package/mint)，可通过以下命令验证你的 OpenAPI 文档：`mint validate`。

<Note>
  Swagger 的 OpenAPI 指南面向 OpenAPI v3.0，但其中几乎所有信息同样适用于 v3.1。关于 v3.0 与 v3.1 的差异，请参阅 OpenAPI 博客中的 [Migrating from OpenAPI 3.0 to 3.1.0](https://www.openapis.org/blog/2021/02/16/migrating-from-openapi-3-0-to-3-1-0)。
</Note>

<div id="specify-the-base-url-for-your-api">
  ### 指定 API 的基础 URL
</div>

要启用 API playground，请在 OpenAPI 规范中添加 `servers` 字段，并填写 API 的基础 URL。

```json theme={null}
{
  "servers": [
    {
      "url": "https://api.example.com/v1"
    }
  ]
}
```

在 OpenAPI 规范中，不同的 API 端点通过其路径来定义，例如 `/users/{id}`，或直接使用 `/`。基础 URL 用于指明这些路径应追加到哪里。有关如何配置 `servers` 字段的更多信息，请参阅 OpenAPI 文档中的 [API Server and Base Path](https://swagger.io/docs/specification/api-host-and-base-path/)。

API playground 会使用这些服务器 URL 来确定请求的发送目标。如果你指定了多个服务器，将提供一个下拉菜单，允许用户在不同服务器之间切换。如果未指定服务器，API playground 会使用简易模式，因为在没有基础 URL 的情况下无法发送请求。

如果你的 API 的端点分布在不同的 URL 下，你可以为特定路径或操作[覆盖 `servers` 字段](https://swagger.io/docs/specification/v3_0/api-host-and-base-path/#overriding-servers)。

<div id="specify-authentication">
  ### 指定身份验证
</div>

要在 API 文档与操练场中启用身份验证，请在 OpenAPI 规范中配置 `securitySchemes` 和 `security` 字段。API 描述与 API 操练场会根据 OpenAPI 规范中的安全配置自动添加身份验证字段。

<Steps>
  <Step title="定义你的身份验证方式。">
    添加 `securitySchemes` 字段来定义用户如何进行身份验证。

    以下示例展示了 Bearer 身份验证的配置：

    ```json theme={null}
    {
      "components": {
        "securitySchemes": {
          "bearerAuth": {
            "type": "http",
            "scheme": "bearer"
          }
        }
      }
    }
    ```
  </Step>

  <Step title="将身份验证应用到你的端点。">
    添加 `security` 字段以要求进行身份验证。

    ```json theme={null}
    {
      "security": [
        {
          "bearerAuth": []
        }
      ]
    }
    ```
  </Step>
</Steps>

常见的身份验证类型包括：

* [API Keys](https://swagger.io/docs/specification/authentication/api-keys/): 适用于基于 header、query 或 cookie 的密钥。
* [Bearer](https://swagger.io/docs/specification/authentication/bearer-authentication/): 适用于 JWT 或 OAuth 令牌。
* [Basic](https://swagger.io/docs/specification/authentication/basic-authentication/): 适用于用户名与密码。

如果你的 API 中不同的端点需要不同的身份验证方式，你可以为某个操作[覆盖 `security` 字段](https://swagger.io/docs/specification/authentication/#:~:text=you%20can%20apply%20them%20to%20the%20whole%20API%20or%20individual%20operations%20by%20adding%20the%20security%20section%20on%20the%20root%20level%20or%20operation%20level%2C%20respectively.)。

有关定义和应用身份验证的更多信息，请参阅 OpenAPI 文档中的[Authentication](https://swagger.io/docs/specification/authentication/)。

<div id="set-default-values-for-security-schemes">
  #### 为安全方案设置默认值
</div>

在安全方案上使用 `x-default` 扩展，可以在 API playground 中预填身份验证字段。这对于提供占位值或测试凭据非常有用，能帮助用户快速上手。

```json {6} theme={null}
{
  "components": {
    "securitySchemes": {
      "apiKey": {
        "type": "apiKey",
        "in": "header",
        "name": "X-API-Key",
        "x-default": "your-api-key-here"
      }
    }
  }
}
```

`x-default` 扩展支持 `apiKey` 和 `http` bearer 安全方案类型。该值作为 playground 身份验证字段中的默认输入显示。

你还可以在 OpenAPI 规范中的任何 schema 属性上使用 `x-default`，以在 API playground 中设置默认值，而不影响 schema 定义中的 `default` 字段。

<div id="let-visitors-download-your-spec">
  ## 让访客下载你的规范
</div>

通过在 `docs.json` 中将 `"download-spec"` 添加到 `contextual.options`，可在[页面上下文菜单](/zh/organize/settings-structure#contextual)中启用"下载 API 规范"选项：

```json theme={null}
"contextual": {
  "options": ["copy", "download-spec", "chatgpt", "claude"]
}
```

启用后，点击该选项会直接下载你的 OpenAPI 规范。包含多个规范的部署会将它们打包为 `api-specs.zip`。对于使用 `auth` 或 `userAuth` 保护的部署，该选项会隐藏，以防止从受身份验证保护的文档中泄露规范内容。

<div id="customize-your-endpoint-pages">
  ## 自定义端点页面
</div>

在 OpenAPI 规范中添加 `x-mint` 扩展即可自定义端点页面。`x-mint` 扩展可让你进一步控制 API 文档的生成与展示方式。

<div id="metadata">
  ### 元数据
</div>

在任意操作中添加 `x-mint: metadata`，即可覆盖生成的 API 页面的默认元数据。除了 `openapi` 之外，你可以使用 MDX frontmatter 中任意有效的元数据字段。

```json {7-14} theme={null}
{
  "paths": {
    "/users": {
      "get": {
        "summary": "Get users",
        "description": "Retrieve a list of users",
        "x-mint": {
          "metadata": {
            "title": "List all users",
            "sidebarTitle": "List users",
            "description": "获取分页用户数据及筛选选项",
            "og:title": "Display a list of users"
          }
        },
        "parameters": [
          {
            // Parameter configuration
          }
        ]
      }
    }
  }
}
```

你还可以使用 `playground` 和 `groups` metadata 字段，为每个 endpoint 单独控制 playground 的展示：

```json {7-11} theme={null}
{
  "paths": {
    "/admin/users": {
      "post": {
        "summary": "创建管理员用户",
        "x-mint": {
          "metadata": {
            "playground": "auth",
            "groups": ["admin"],
            "public": true
          }
        }
      }
    }
  }
}
```

此配置会让页面对所有人可见，但只有属于 `admin` 组的已认证用户才能使用交互式 Playground。

<div id="content">
  ### 内容
</div>

使用 `x-mint: content` 在自动生成的 API 文档之前添加内容。`x-mint: content` 扩展支持所有 Mintlify MDX 组件和格式。

```json {6-8} theme={null}
{
  "paths": {
    "/users": {
      "post": {
        "summary": "创建用户",
        "x-mint": {
          "content": "## 前提条件\n\n此端点需要管理员权限,并设有速率限制。\n\n<Note>用户邮箱在系统内必须唯一。</Note>"
        },
        "parameters": [
          {
            // 参数配置
          }
        ]
      }
    }
  }
}
```

<div id="href">
  ### href
</div>

使用 `x-mint: href` 设置自动生成的端点页面的 URL。当存在 `x-mint: href` 时，生成的 API 页面将使用指定的 URL，而不是默认自动生成的 URL。

```json {6-8, 14-16} theme={null}
{
  "paths": {
    "/legacy-endpoint": {
      "get": {
        "summary": "旧版端点",
        "x-mint": {
          "href": "/deprecated-endpoints/legacy-endpoint"
        }
      }
    },
    "/documented-elsewhere": {
      "post": {
        "summary": "特殊端点",
        "x-mint": {
          "href": "/guides/special-endpoint-guide"
        }
      }
    }
  }
}
```

<div id="parameter-pills">
  ### 参数标签
</div>

使用任意 schema 上的 `x-mint.pre` 和 `x-mint.post`，为 API 参考和 playground 中的参数添加自定义标签。pre 标签会渲染在参数名称之前，post 标签会渲染在参数名称之后，与 Mintlify 内置的 `required`、`read-only` 和 `write-only` 等标签并排显示。

这两个字段都接受字符串数组。每个字符串都会成为一个独立的标签。

```json {7-10} theme={null}
{
  "components": {
    "schemas": {
      "User": {
        "properties": {
          "email": {
            "type": "string",
            "x-mint": {
              "pre": ["PII"],
              "post": ["indexed", "unique"]
            }
          }
        }
      }
    }
  }
}
```

若要在所有参数上显示任意 OpenAPI 规范字段作为标签，而无需逐个修改 schema，请在 `docs.json` 中配置 [`api.params.post`](/zh/organize/settings-api#api-params)。列出你希望显示的字段键名，Mintlify 会从 schema 中读取每个值，并自动渲染相应的标签。

```json theme={null}
{
  "api": {
    "params": {
      "post": ["nullable", "x-internal"]
    }
  }
}
```

通过此配置，类似 `{ "type": "string", "nullable": true, "x-internal": "admin" }` 的属性会在其名称旁渲染 `nullable` 和 `admin` 标签。post 标签按以下顺序显示：内置标签（`read-only`、`write-only`）、由 `api.params.post` 配置驱动的标签，然后是逐属性配置的 `x-mint.post` 标签。

<div id="group-display-names">
  ### 分组显示名称
</div>

使用 tag 对象上的 `x-group` 扩展为某个 tag 的导航分组设置自定义显示名称。默认情况下，Mintlify 将 tag 的 `name` 同时用作导航分组标签和 URL 路径段。`x-group` 扩展会覆盖分组标签，同时保留 tag 名称用于 URL。

当你希望使用一个易于阅读的分组名称，而该名称与 API 路径中使用的 tag 不同时，这非常有用。

```json {4-9} theme={null}
{
  "tags": [
    {
      "name": "user-management",
      "description": "Endpoints for managing users",
      "x-group": "User Management"
    }
  ],
  "paths": {
    "/users": {
      "get": {
        "tags": ["user-management"],
        "summary": "List users"
      }
    }
  }
}
```

在此示例中，导航分组显示为 "User Management"，但生成的页面 URL 仍使用 `user-management` tag 名称作为路径段。

<div id="auto-populate-api-pages">
  ## 自动填充 API 页面
</div>

在你的 `docs.json` 中为任意导航元素添加一个 `openapi` 字段，可自动生成 OpenAPI 端点页面。你可以控制这些页面在导航结构中的位置，既可作为独立的 API 区块，也可与其他页面并列展示。

`openapi` 字段可接受你文档仓库中的路径，或指向托管 OpenAPI 文档的 URL。

<Tip>
  当你使用 URL 指定 OpenAPI 规范时，规范的更改不会触发 Git 推送，因此你的文档不会自动重新部署。为了保持文档同步，请在生成或更新规范的同一个 CI 操作中调用 [Trigger deployment](/zh/api/update/trigger) API 端点。这样你的文档就会自动更新，无需从仪表板手动触发部署。
</Tip>

生成的端点页面具有以下默认元数据值：

* `title`：若存在，则取该操作的 `summary` 字段；若没有 `summary`，Mintlify 会根据 HTTP 方法与端点生成标题。
* `description`：若存在，则取该操作的 `description` 字段。
* `version`：若存在，则取父级锚点或选项卡中的 `version` 值。
* `deprecated`：取该操作的 `deprecated` 字段。若为 `true`，则会在侧边导航和端点页面的端点标题旁显示“已弃用”标签。

<Tip>
  若要将特定端点从自动生成的 API 页面中排除，请在 OpenAPI 规范中的该操作上添加 [x-hidden](/zh/api-playground/managing-page-visibility#x-hidden) 属性。
</Tip>

将端点页面添加到文档中有两种方式：

1. **独立的 API 区块**：在导航元素中引用 OpenAPI 规范以创建独立的 API 区块。
2. **选择性端点**：在导航中与其他页面并列引用特定端点。

<div id="dedicated-api-sections">
  ### 专用 API 部分
</div>

在某个导航元素中仅添加一个 `openapi` 字段 (不包含其他页面) ，即可生成专用的 API 部分。规范中的所有端点都会出现在生成的部分中。

```json {5} theme={null}
"navigation": {
  "tabs": [
    {
        "tab": "API 参考",
        "openapi": "https://petstore3.swagger.io/api/v3/openapi.json"
    }
  ]
}
```

若要在文档的不同部分组织多个 OpenAPI 规范，请在导航层级中将每个规范分配到不同的分组。每个分组都可以引用其各自的 OpenAPI 规范。

```json {8-11, 15-18} theme={null}
"navigation": {
  "tabs": [
    {
      "tab": "API 参考",
      "groups": [
        {
          "group": "用户 API",
          "openapi": {
            "source": "/path/to/users-openapi.json",
            "directory": "users-api-reference"
          }
        },
        {
          "group": "管理 API",
          "openapi": {
            "source": "/path/to/admin-openapi.json",
            "directory": "admin-api-reference"
          }
        }
      ]
    }
  ]
}
```

<Note>
  `directory` 字段为可选项，用于指定 Mintlify 将生成的 API 页面存放在文档仓库中的位置。若未指定，则默认使用仓库中的 `api-reference` 目录。
</Note>

<div id="selective-endpoints">
  ### 选择性端点
</div>

当你希望更精确地控制端点在文档中的展示位置时，可以在导航中引用特定端点。此方法允许你在其他内容旁生成 API 端点的页面。你也可以用这种方法将来自不同 OpenAPI 规范的端点混合在一起。

<div id="set-a-default-openapi-spec">
  #### 设置默认 OpenAPI 规范
</div>

为导航元素配置默认的 OpenAPI 规范，然后在 `pages` 字段中引用特定的端点。

```json {12, 15-16} theme={null}
"navigation": {
  "tabs": [
    {
      "tab": "快速入门",
      "pages": [
        "quickstart",
        "installation"
      ]
    },
    {
      "tab": "API 参考",
      "openapi": "/path/to/openapi.json",
      "pages": [
        "api-overview",
        "GET /users",
        "POST /users",
        "guides/authentication"
      ]
    }
  ]
}
```

任何符合 `METHOD /path` 格式的页面条目，都会基于默认的 OpenAPI 规范为该端点生成一个 API 页面。

<div id="openapi-spec-inheritance">
  #### OpenAPI 规范继承
</div>

子级导航项会继承其父级的 OpenAPI 规范，除非它们定义了自己的规范。

```json {3, 7-8, 11, 13-14} theme={null}
{
  "group": "API 参考",
  "openapi": "/path/to/openapi-v1.json",
  "pages": [
    "概述",
    "身份验证",
    "GET /users",
    "POST /users",
    {
      "group": "订单",
      "openapi": "/path/to/openapi-v2.json",
      "pages": [
        "GET /orders",
        "POST /orders"
      ]
    }
  ]
}
```

<div id="individual-endpoints">
  #### 单个端点
</div>

通过包含文件路径，可在不设置默认 OpenAPI 规范的情况下引用特定端点。你也可以在同一文档部分中引用来自多个 OpenAPI 规范的端点。

```json {5-6} theme={null}
"navigation": {
  "pages": [
    "introduction",
    "user-guides",
    "/path/to/users-openapi.json POST /users",
    "/path/to/orders-openapi.json GET /orders"
  ]
}
```

当你需要从不同规范中选取某些单独的端点、只想包含特定端点，或希望将端点与其他类型的文档一并呈现时，这种方法非常有用。

<div id="create-mdx-pages-from-your-openapi-specification">
  ## 从你的 OpenAPI 规范创建 MDX 页面
</div>

若需对单个端点页面进行更细粒度的控制，可基于你的 OpenAPI 规范创建 MDX 页面。这样你可以自定义页面元数据与内容，并在导航中对页面重新排序或将其排除，同时仍可使用自动生成的参数与响应。

有两种方式使用独立的 MDX 页面为你的 OpenAPI 规范编写文档：

* 在前置参数 (frontmatter) 中使用 `openapi` 字段为端点编写文档。
* 在前置参数 (frontmatter) 中使用 `openapi-schema` 字段为数据模型编写文档。

<div id="document-endpoints">
  ### 编写端点文档
</div>

为每个端点创建一个页面，并在 frontmatter 中使用 `openapi` 字段指定要展示的 OpenAPI 操作。

<CodeGroup>
  ```mdx Example theme={null}
  ---
  title: "Get users"
  description: "Returns all plants from the system that the user has access to"
  openapi: "/path/to/openapi-1.json GET /users"
  deprecated: true
  version: "1.0"
  ---
  ```

  ```mdx Format theme={null}
  ---
  title: "title of the page"
  description: "description of the page"
  openapi: openapi-file-path method path
  deprecated: boolean (not required)
  version: "version-string" (not required)
  ---
  ```
</CodeGroup>

方法和路径必须与您的 OpenAPI 规范完全一致。若您有多个 OpenAPI 规范，请在引用中包含对应规范文件的路径。您也可以在 `docs.json` 中引用外部 OpenAPI URL。

<div id="autogenerate-endpoint-pages">
  #### 自动生成端点页面
</div>

要根据你的 OpenAPI 规范自动生成 MDX 文件，请使用 Mintlify 的 [scraper](https://www.npmjs.com/package/@mintlify/scraping)。

```bash theme={null}
npx @mintlify/scraping@latest openapi-file <path-to-openapi-file> -o <folder-name>
```

<Tip>
  添加 `-o` 标志以指定输出文件夹。若未指定文件夹，文件将生成在工作目录中。
</Tip>

<div id="document-data-models">
  ### 文档数据模型
</div>

在 frontmatter 中使用 `openapi-schema` 字段，为 OpenAPI 规范的 `components.schemas` 下定义的每个数据结构各创建一个页面。

<CodeGroup>
  ```mdx Example theme={null}
  ---
  openapi-schema: OrderItem
  ---
  ```

  ```mdx Format theme={null}
  ---
  openapi-schema: "openapi-file-path schema-key"
  ---
  ```
</CodeGroup>

如果在多个文件中存在同名 schema，请明确指定 OpenAPI 文件：

<CodeGroup>
  ```mdx Example theme={null}
  ---
  openapi-schema: en-schema.json OrderItem
  ---
  ```

  ```mdx Format theme={null}
  ---
  openapi-schema: "path-to-schema-file schema-key"
  ---
  ```
</CodeGroup>

<div id="webhooks">
  ## Webhooks
</div>

Webhook 是你的 API 在事件发生时用于通知外部系统的 HTTP 回调。OpenAPI 3.1+ 文档支持 webhook。

在你的 OpenAPI 文档中，与 `paths` 字段并列添加一个 `webhooks` 字段。

有关定义 Webhook 的更多信息，请参阅 OpenAPI 文档中的 [Webhooks](https://spec.openapis.org/oas/v3.1.0#oasWebhooks)。

要为某个 Webhook (OpenAPI 3.1+) 创建 MDX 页面，请使用 `webhook` 替代某个 HTTP 方法：

```mdx theme={null}
---
title: "订单更新 webhook"
description: "当订单更新时触发"
openapi: "openapi.json webhook orderUpdated"
---
```

Webhook 名称必须与 OpenAPI 规范中 `webhooks` 字段中的键完全一致。

<div id="callbacks">
  ## 回调（Callbacks）
</div>

回调用于描述你的 API 向调用方提供的 URL 发送的带外请求，例如与特定操作关联的事件通知。当 OpenAPI 操作定义了 `callbacks` 时，Mintlify 会在端点页面的请求体和响应部分之间，以可折叠区域的形式呈现这些回调。每个回调都会显示其 HTTP 方法和表达式，并复用与父操作相同的请求体和响应组件。

你无需进行任何配置即可显示回调。如果你的 OpenAPI 规范在某个操作上定义了 `callbacks`，它们会自动出现在生成的端点页面上。

有关定义回调的更多信息，请参阅 OpenAPI 文档中的 [Callbacks](https://spec.openapis.org/oas/v3.1.0#callback-object)。

在操作上定义回调的示例：

```yaml theme={null}
paths:
  /subscribe:
    post:
      summary: 订阅事件
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                callbackUrl:
                  type: string
                  format: uri
      responses:
        "201":
          description: 订阅已创建
      callbacks:
        orderUpdated:
          "{$request.body#/callbackUrl}":
            post:
              requestBody:
                required: true
                content:
                  application/json:
                    schema:
                      type: object
                      properties:
                        orderId:
                          type: string
                        status:
                          type: string
              responses:
                "200":
                  description: 已接收回调
```
