write-openapi

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

GitBook OpenAPI

GitBook OpenAPI

GitBook turns an OpenAPI document into interactive, testable API reference blocks. You give it a spec (as JSON or YAML), and it renders endpoints, parameters, schemas, auth, and an in-page request runner. Most of the customization happens inside the spec itself through
x-*
extensions, not in the GitBook UI, so the bulk of any task here is editing OpenAPI YAML correctly.
This skill covers the full surface: getting a spec into GitBook, generating reference pages, structuring navigation, making the "Test it" runner work, controlling how operations and schemas display, and automating updates from CI/CD.
GitBook 可将 OpenAPI 文档转换为交互式、可测试的 API 参考区块。你向它提供一份规范(JSON 或 YAML),它便会渲染端点、参数、schema、认证机制和页内请求运行器。大多数自定义配置都发生在规范内部,通过
x-*
扩展完成,而不是在 GitBook UI 中操作,因此这里的多数任务本质上都是正确编辑 OpenAPI YAML。
此 skill 覆盖完整功能面:将规范导入 GitBook、生成参考页面、组织导航、让“Test it”运行器正常工作、控制操作与 schema 的显示方式,以及通过 CI/CD 自动执行更新。

How you can talk to GitBook

如何与 GitBook 交互

Most of this skill — editing the OpenAPI YAML/JSON itself — is transport-agnostic. But getting a spec into GitBook, or generating/inserting reference pages, does touch GitBook, and there's more than one way to do that: GitBook's MCP server and the REST API. Check what's actually available in the current session and prefer MCP first: if GitBook MCP tools are already connected, use them for anything they cover (publishing/updating a spec, generating reference pages) instead of making direct API calls. Don't run a detection script for this — you already know your own available tools/MCP connections; just use that awareness.
The steps below are described as outcomes ("add the spec", "generate the reference pages") rather than tied to one transport, so they apply whichever you use. If GitBook MCP tools are connected, call those directly — their own schemas describe their parameters. If you're on the REST API path instead, the exact endpoints and request bodies are in "Add or update a specification" below.
  • GitBook MCP — a full read/write surface over the same capabilities described below, not a narrower view. If it isn't connected yet and the task is substantial enough to benefit (publishing a new spec, generating a full reference — not a one-off tweak), offer to set it up:
    claude mcp add --transport http gitbook-mcp https://mcp.gitbook.com/mcp
    (then
    /mcp
    to complete OAuth sign-in — or append
    --header "Authorization: Bearer $GITBOOK_TOKEN"
    to skip the browser flow). Codex equivalent:
    codex mcp add gitbook-mcp --url https://mcp.gitbook.com/mcp
    . Note: this is a different server from GitBook's separate, read-only "published docs" MCP, which only exposes already-published content.
  • REST API (
    https://api.gitbook.com/v1
    ) — the fallback when MCP isn't connected, or for anything MCP doesn't cover. Needs
    GITBOOK_TOKEN
    as a bearer header on every request.
The same personal access token (from https://app.gitbook.com/account/developer) works as the bearer token for both. MCP additionally supports OAuth as a friendlier alternative to pasting a token.
If you end up needing a token (REST API path, or MCP without OAuth), check for it at the start of the session:
bash
[ -n "$GITBOOK_TOKEN" ] && echo "Token found" || echo "GITBOOK_TOKEN is not set"
If
GITBOOK_TOKEN
is not set, ask the user directly:
  1. Tell them they need a GitBook personal access token. Direct them to https://app.gitbook.com/account/developer to create one.
  2. Ask them to paste the token into the conversation. Immediately export it as an environment variable (
    export GITBOOK_TOKEN=<pasted value>
    ) and don't repeat it back in your response.
  3. Do not proceed with any API calls until the token is confirmed present in the environment.
Never write the token to a file, never echo it back in a response, never commit it.
The GitBook CLI's
gitbook openapi publish
command (see "Add or update a specification" below) reaches the same underlying capability as the API and MCP — it's a convenience wrapper, not a separate feature set, and authenticates with the same
GITBOOK_TOKEN
.
此 skill 的大部分内容——直接编辑 OpenAPI YAML/JSON——与传输方式无关。但将规范导入 GitBook,或生成/插入参考页面,确实会涉及 GitBook,而且方式不止一种:GitBook 的 MCP server 和 REST API。检查当前会话中实际可用的工具,并优先使用 MCP:如果已连接 GitBook MCP 工具,对于其覆盖的操作(发布/更新规范、生成参考页面),应使用这些工具,而不是直接调用 API。不要运行检测脚本——你本来就知道自己可用的工具/MCP 连接;直接利用这些信息即可。
以下步骤按结果(“添加规范”“生成参考页面”)而非特定传输方式来描述,因此无论使用哪种方式都适用。如果已连接 GitBook MCP 工具,直接调用即可——其自身的 schema 会说明参数。如果改走 REST API 路径,确切的端点和请求体见下文“添加或更新规范”。
  • GitBook MCP — 对以下所有能力提供完整的读写接口,并非功能更窄的视图。如果尚未连接,而任务规模足以从连接中获益(发布新规范、生成完整参考文档,而非一次性微调),可主动提出协助配置:
    claude mcp add --transport http gitbook-mcp https://mcp.gitbook.com/mcp
    (随后运行
    /mcp
    完成 OAuth 登录——或附加
    --header "Authorization: Bearer $GITBOOK_TOKEN"
    以跳过浏览器流程)。Codex 等效命令:
    codex mcp add gitbook-mcp --url https://mcp.gitbook.com/mcp
    。请注意,它与 GitBook 另一个独立的只读“published docs”MCP 不同,后者只暴露已经发布的内容。
  • REST API(
    https://api.gitbook.com/v1
    )— 当未连接 MCP,或 MCP 未覆盖某些操作时使用。每次请求都需要在请求头中通过 Bearer 方式传递
    GITBOOK_TOKEN
    。
同一个 personal access token(获取地址:https://app.gitbook.com/account/developer)对 API 和 MCP 都可用作 Bearer token。MCP 还支持 OAuth,作为粘贴 token 之外更友好的替代方案。
如果最终需要 token(使用 REST API,或 MCP 未采用 OAuth),请在会话开始时检查:
bash
[ -n "$GITBOOK_TOKEN" ] && echo "Token found" || echo "GITBOOK_TOKEN is not set"
如果未设置
GITBOOK_TOKEN
,直接询问用户:
  1. 告知用户需要 GitBook personal access token,并引导他们前往 https://app.gitbook.com/account/developer 创建。
  2. 请用户将 token 粘贴到对话中。随即将其导出为环境变量(
    export GITBOOK_TOKEN=<pasted value>
    ),且不要在回复中重复 token 内容。
  3. 在确认环境中已经存在 token 之前,不要发起任何 API 调用。
绝不要将 token 写入文件,绝不要在回复中回显 token,也绝不要提交 token。
GitBook CLI 的
gitbook openapi publish
命令(参见下文“添加或更新规范”)使用的是与 API 和 MCP 相同的底层能力——它只是一个便捷包装器,并非独立的功能集,并使用相同的
GITBOOK_TOKEN
进行认证。

Key facts to know first

首先需要了解的关键事实

These shape almost every decision, so internalize them before editing anything.
  • Supported versions. GitBook accepts Swagger 2.0 and OpenAPI 3.0 specs. Some features need newer versions: webhooks require OpenAPI 3.1, and the official
    parent
    tag property requires OpenAPI 3.2+ (use
    x-parent
    on 3.0.x and 3.1.x). Always check the spec's
    openapi:
    /
    swagger:
    version before reaching for a version-gated feature.
  • The "Test it" runner is powered by Scalar. It runs requests from the reader's browser unless you route them through GitBook's proxy.
  • A spec's source is a file or a URL — and that's what determines updates, not which transport (MCP, API, CLI, or UI) you used to set it. URL sources auto-refresh every 6 hours; file sources only change when re-uploaded or re-published.
  • x-*
    extensions are namespaced and safe to keep in a shared spec.
    Tools that do not understand a given extension ignore it, so a spec instrumented for GitBook still validates and works elsewhere.
这些事实几乎会影响所有决策,因此编辑任何内容之前应先充分掌握。
  • 支持的版本。 GitBook 接受 Swagger 2.0 和 OpenAPI 3.0 规范。部分功能需要更新的版本:webhook 需要 OpenAPI 3.1,官方
    parent
    tag 属性需要 OpenAPI 3.2+(在 3.0.x 和 3.1.x 中使用
    x-parent
    )。使用受版本限制的功能前,务必检查规范中的
    openapi:
    /
    swagger:
    版本。
  • “Test it”运行器由 Scalar 提供支持。 除非将请求路由到 GitBook 的 proxy,否则它会从读者的浏览器中发起请求。
  • 规范的来源可以是文件或 URL,决定更新方式的也是来源,而不是导入时使用的传输方式(MCP、API、CLI 或 UI)。 URL 来源每 6 小时自动刷新;文件来源只有在重新上传或重新发布后才会改变。
  • x-*
    扩展带有命名空间,可安全保留在共享规范中。
    不理解某个扩展的工具会忽略它,因此为 GitBook 配置过的规范仍可正常验证并用于其他环境。

What are you trying to do?

你想完成什么?

Match the task to the right section. For the deeper reference material, two files live alongside this one:
  • Editing or looking up any
    x-*
    extension, with full YAML for each: read
    references/extensions.md
    .
  • Making the interactive runner work end to end (auth schemes, servers, CORS, proxy): read
    references/test-it-setup.md
    .
TaskGo to
Get a spec into GitBook, or update one"Add or update a specification"
Generate reference pages, or drop a single endpoint/schema into a page"Insert an API reference"
Split, order, nest, title, or icon your pages"Structure the reference"
Make "Test it" work, fix CORS, configure auth"Configure the Test it runner" +
references/test-it-setup.md
Mark an endpoint experimental, deprecated, or hidden"Manage operation lifecycle"
Look up the exact name/scope of an extension"Extensions cheat-sheet" +
references/extensions.md
Auto-publish the spec from a pipeline"Automate with CI/CD"
根据任务选择对应章节。若需查阅更深入的资料,本文档旁还有两个文件:
  • 编辑或查找任何
    x-*
    扩展及其完整 YAML:阅读
    references/extensions.md
    。
  • 让交互式运行器端到端正常工作(认证方案、服务器、CORS、proxy):阅读
    references/test-it-setup.md
    。
任务前往
将规范导入 GitBook 或更新规范“添加或更新规范”
生成参考页面,或将单个端点/schema 放入页面“插入 API 参考”
拆分、排序、嵌套页面,或设置页面标题与图标“组织参考文档结构”
让“Test it”正常工作、修复 CORS、配置认证“配置 Test it 运行器” +
references/test-it-setup.md
将端点标记为实验性、已弃用或隐藏“管理操作生命周期”
查询扩展的确切名称和作用范围“扩展速查表” +
references/extensions.md
从流水线自动发布规范“使用 CI/CD 自动化”

Add or update a specification

添加或更新规范

A spec must exist in the organization before any block or page can reference it. Adding and updating are the same underlying operation on every transport — pick whichever you have per "How you can talk to GitBook" above. Whichever you use, give the spec a name/slug up front: it's how you reference it later and how you tell multiple specs apart.
GitBook MCP — if connected, use its spec tool directly for creating or updating a spec from either a file or a URL; its schema covers both source types.
REST API — create with a URL source:
bash
curl -s -X POST -H "Authorization: Bearer $GITBOOK_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"slug": "<spec-name>", "source": {"url": "<hosted-url>"}}' \
  https://api.gitbook.com/v1/orgs/$ORG_ID/openapi
or from a file:
bash
curl -s -X POST -H "Authorization: Bearer $GITBOOK_TOKEN" \
  -F "slug=<spec-name>" \
  -F "file=@./openapi.yaml" \
  https://api.gitbook.com/v1/orgs/$ORG_ID/openapi
Update (replace) an existing spec the same way against
PATCH /v1/orgs/{orgId}/openapi/{specId}
.
GitBook CLI — a thin wrapper over the same API call, useful in scripts and pipelines (same command adds or updates; running it against a URL also forces a refresh):
bash
gitbook openapi publish --spec <spec-name> --organization <organization-id> <path-or-url>
For pipeline automation see "Automate with CI/CD". CLI details: https://gitbook.com/docs/developers/integrations/reference
GitBook app UI — open the OpenAPI section in the sidebar, click Add specification, name it, then choose to upload a file or enter a hosted URL. Updating depends on the source: URL sources check every 6 hours automatically (click Check for updates to pull immediately; switch File to URL via Edit in the breadcrumb actions menu); file sources need Update to upload a new version.
在任何区块或页面引用规范之前,该规范必须已存在于组织中。无论使用哪种传输方式,添加和更新在底层都是同一项操作——根据上文“如何与 GitBook 交互”选择可用方式。无论采用哪种方式,都应预先为规范指定名称/slug:后续将使用它来引用规范,并区分多个规范。
GitBook MCP — 如果已连接,直接使用其规范工具从文件或 URL 创建或更新规范;其 schema 同时涵盖这两种来源类型。
REST API — 使用 URL 来源创建:
bash
curl -s -X POST -H "Authorization: Bearer $GITBOOK_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"slug": "<spec-name>", "source": {"url": "<hosted-url>"}}' \
  https://api.gitbook.com/v1/orgs/$ORG_ID/openapi
或从文件创建:
bash
curl -s -X POST -H "Authorization: Bearer $GITBOOK_TOKEN" \
  -F "slug=<spec-name>" \
  -F "file=@./openapi.yaml" \
  https://api.gitbook.com/v1/orgs/$ORG_ID/openapi
更新(替换)现有规范时,使用相同方式调用
PATCH /v1/orgs/{orgId}/openapi/{specId}
。
GitBook CLI — 它是对同一 API 调用的轻量包装器,适用于脚本和流水线;同一命令既可添加也可更新规范,对 URL 执行该命令还会强制刷新:
bash
gitbook openapi publish --spec <spec-name> --organization <organization-id> <path-or-url>
有关流水线自动化,请参阅“使用 CI/CD 自动化”。CLI 详情:https://gitbook.com/docs/developers/integrations/reference
GitBook 应用 UI — 打开侧边栏中的 OpenAPI 区域,点击 Add specification,填写名称,然后选择上传文件或输入托管 URL。更新方式取决于来源:URL 来源每 6 小时自动检查一次(点击 Check for updates 可立即拉取;可通过面包屑操作菜单中的 Edit 将 File 切换为 URL);文件来源需要点击 Update 上传新版本。

Insert an API reference

插入 API 参考

Once the spec exists, surface it in the docs one of two ways.
Generate a full set of pages (recommended for a complete reference). In the target space's table of contents, click Add new... at the bottom, then OpenAPI Reference, pick the spec, and insert. GitBook creates one page per tag in the spec (see "Structure the reference"), and optionally a models page listing every schema. These pages keep updating whenever the spec updates.
Insert a single operation or schema into an existing page. Press
/
, search for OpenAPI, pick the spec, choose Continue, then select the specific operations and/or schemas to embed.
Block syntax. When writing GitBook markdown directly, an OpenAPI operation block looks like this (the inner line repeats the source):
{% openapi src="https://petstore3.swagger.io/api/v3/openapi.json" path="/pet" method="post" %}
https://petstore3.swagger.io/api/v3/openapi.json
{% endopenapi %}
To highlight one or more schemas inline (for example inside a tag description), use the schemas block:
{% openapi-schemas spec="petstore" schemas="Pet" grouped="false" %}
The Pet object
{% endopenapi-schemas %}
规范存在后,可以通过两种方式之一将其呈现在文档中。
生成完整页面集(适合完整的参考文档,推荐使用)。 在目标 space 的目录底部点击 Add new...,然后选择 OpenAPI Reference,选定规范并插入。GitBook 会为规范中的每个 tag 创建一个页面,还可以选择创建一个列出所有 schema 的 models 页面。这些页面会在规范更新时持续同步更新。
将单个操作或 schema 插入现有页面。 按
/
,搜索 OpenAPI,选定规范,点击 Continue,然后选择要嵌入的具体操作和/或 schema。
区块语法。 直接编写 GitBook Markdown 时,OpenAPI 操作区块如下所示(内层一行会重复源地址):
{% openapi src="https://petstore3.swagger.io/api/v3/openapi.json" path="/pet" method="post" %}
https://petstore3.swagger.io/api/v3/openapi.json
{% endopenapi %}
若要内联突出显示一个或多个 schema(例如放在 tag 描述中),可使用 schemas 区块:
{% openapi-schemas spec="petstore" schemas="Pet" grouped="false" %}
The Pet object
{% endopenapi-schemas %}

Structure the reference

组织参考文档结构

GitBook builds navigation from the spec's
tags
, so structuring the reference is mostly structuring tags. Full YAML for every extension named here is in
references/extensions.md
.
  • Split operations across pages: give operations the same tag, and each tag becomes its own page.
    yaml
    paths:
      /pet:
        put:
          tags:
            - pet
          summary: Update an existing pet.
          operationId: updatePet
  • Order pages: page order follows the order of entries in the top-level
    tags
    array.
    yaml
    tags:
      - name: pet
      - name: store
      - name: user
  • Nest pages into groups: use
    parent
    (OpenAPI 3.2+) or
    x-parent
    (3.0.x/3.1.x) to point a tag at its parent tag.
    yaml
    tags:
      - name: everything
      - name: pet
        x-parent: everything
      - name: store
        x-parent: everything
    If a parent page has no
    description
    , GitBook automatically renders a card-based layout linking its sub-pages.
  • Add titles, icons, and descriptions per page via tag-level extensions. Icons accept any Font Awesome name (https://fontawesome.com/search).
    yaml
    tags:
      - name: pet
        x-page-title: Pet              # title in the table of contents and page header
        x-page-icon: dog               # icon in the ToC and next to the title
        x-page-description: Pets are amazing!   # shown just above the title
        description: Everything about your Pets # the page body
  • Write rich descriptions. Tag
    description
    fields accept GitBook markdown, including advanced blocks such as
    {% tabs %}
    , so a page intro can be far more than plain text.
  • Document webhooks (OpenAPI 3.1) with a top-level
    webhooks
    field that mirrors
    paths
    :
    yaml
    openapi: 3.1.0
    webhooks:
      newPet:
        post:
          summary: New pet event
          requestBody:
            content:
              application/json:
                schema:
                  $ref: "#/components/schemas/Pet"
          responses:
            "200":
              description: Received successfully
GitBook 根据规范中的
tags
构建导航,因此组织参考文档主要就是组织 tag。本文提到的每个扩展的完整 YAML 均位于
references/extensions.md
。
  • 将操作拆分到不同页面: 为操作指定相同的 tag,每个 tag 会成为一个独立页面。
    yaml
    paths:
      /pet:
        put:
          tags:
            - pet
          summary: Update an existing pet.
          operationId: updatePet
  • 排序页面: 页面顺序遵循顶层
    tags
    数组中条目的顺序。
    yaml
    tags:
      - name: pet
      - name: store
      - name: user
  • 将页面嵌套到分组中: 使用
    parent
    (OpenAPI 3.2+)或
    x-parent
    (3.0.x/3.1.x)将一个 tag 指向其父 tag。
    yaml
    tags:
      - name: everything
      - name: pet
        x-parent: everything
      - name: store
        x-parent: everything
    如果父页面没有
    description
    ,GitBook 会自动呈现基于卡片的布局,并链接到其子页面。
  • 通过 tag 级扩展为每个页面添加标题、图标和描述。 图标支持任意 Font Awesome 名称(https://fontawesome.com/search)。
    yaml
    tags:
      - name: pet
        x-page-title: Pet              # title in the table of contents and page header
        x-page-icon: dog               # icon in the ToC and next to the title
        x-page-description: Pets are amazing!   # shown just above the title
        description: Everything about your Pets # the page body
  • 编写内容丰富的描述。 Tag 的
    description
    字段支持 GitBook Markdown,包括
    {% tabs %}
    等高级区块,因此页面简介可以远不止于纯文本。
  • 记录 webhook(OpenAPI 3.1),使用与
    paths
    对应的顶层
    webhooks
    字段:
    yaml
    openapi: 3.1.0
    webhooks:
      newPet:
        post:
          summary: New pet event
          requestBody:
            content:
              application/json:
                schema:
                  $ref: "#/components/schemas/Pet"
          responses:
            "200":
              description: Received successfully

Configure the Test it runner

配置 Test it 运行器

The interactive runner only works as well as the spec describes it. The runner targets the URLs in the
servers
array and can only present auth that the spec declares under
components.securitySchemes
. For anything non-trivial (Bearer/JWT, API key, OAuth2, multiple or templated server URLs, per-operation overrides), read
references/test-it-setup.md
, which has copy-paste YAML for each pattern.
Two quick decisions you will hit constantly:
  • "Why isn't my spec loading?" / "Why does Test it fail?" (URL specs). This is almost always CORS. A URL-added spec requires the API to allow cross-origin GET requests from the docs origin (for example
    https://your-site.gitbook.io
    or your custom domain). Public, credential-free endpoints can return
    Access-Control-Allow-Origin: *
    .
  • API can't enable CORS? Route requests through GitBook's proxy with
    x-enable-proxy: true
    (at the root for the whole spec, or on a single operation; the operation value wins). The proxy forwards all HTTP methods, headers, cookies, and bodies, but only to URLs listed in
    servers
    , so make sure every base URL you want to test is in that array. Details in
    references/test-it-setup.md
    .
To remove the runner from an endpoint (or the whole spec), set
x-hideTryItPanel: true
.
交互式运行器的功能取决于规范对接口的描述是否准确。运行器会请求
servers
数组中的 URL,并且只能提供规范在
components.securitySchemes
下声明的认证方式。对于任何非简单场景(Bearer/JWT、API key、OAuth2、多个或带模板的服务器 URL、操作级覆盖),请阅读
references/test-it-setup.md
,其中为每种模式提供了可直接复制的 YAML。
以下是经常需要做出的两个快速判断:
  • “为什么我的规范无法加载?”/“为什么 Test it 无法工作?”(URL 规范)。 这几乎总是由 CORS 引起的。通过 URL 添加的规范要求 API 允许从文档源(例如
    https://your-site.gitbook.io
    或自定义域名)发起跨域 GET 请求。公开且无需凭据的端点可以返回
    Access-Control-Allow-Origin: *
    。
  • API 无法启用 CORS? 通过设置
    x-enable-proxy: true
    将请求路由到 GitBook 的 proxy(可在规范根级别设置,也可在单个操作上设置;操作级值优先)。Proxy 会转发所有 HTTP 方法、请求头、cookie 和请求体,但仅允许访问
    servers
    中列出的 URL,因此请确保所有需要测试的基础 URL 均在该数组中。详情参见
    references/test-it-setup.md
    。
若要移除某个端点或整个规范中的运行器,请设置
x-hideTryItPanel: true
。

Manage operation lifecycle

管理操作生命周期

Common when endpoints are not production-ready or are being phased out. All of these are operation-level unless noted.
  • Not stable yet:
    x-stability: experimental
    (also
    alpha
    or
    beta
    ).
  • Deprecated:
    deprecated: true
    . Deprecated endpoints show a deprecation warning on the published site.
  • Deprecated with an end date: add
    x-deprecated-sunset: 2030-12-05
    (ISO 8601,
    YYYY-MM-DD
    ).
  • Hide an endpoint entirely:
    x-internal: true
    (or its alias
    x-gitbook-ignore: true
    ).
  • Hide one response sample: set
    x-hideSample: true
    on that response object (for example under
    responses.200
    ).
yaml
paths:
  /pet:
    put:
      operationId: updatePet
      x-stability: experimental
      deprecated: true
      x-deprecated-sunset: 2030-12-05
当端点尚未达到生产就绪状态或正在逐步淘汰时,通常需要使用这些功能。除非另有说明,以下内容均作用于操作级别。
  • 尚不稳定:
    x-stability: experimental
    (也可使用
    alpha
    或
    beta
    )。
  • 已弃用:
    deprecated: true
    。已弃用的端点会在已发布站点中显示弃用警告。
  • 弃用并设置结束日期: 添加
    x-deprecated-sunset: 2030-12-05
    (ISO 8601,
    YYYY-MM-DD
    )。
  • 完全隐藏端点:
    x-internal: true
    (或其别名
    x-gitbook-ignore: true
    )。
  • 隐藏单个响应示例: 在对应响应对象上设置
    x-hideSample: true
    (例如
    responses.200
    下方)。
yaml
paths:
  /pet:
    put:
      operationId: updatePet
      x-stability: experimental
      deprecated: true
      x-deprecated-sunset: 2030-12-05

Extensions cheat-sheet

扩展速查表

Every GitBook-supported extension at a glance. For the full YAML example of any row, open
references/extensions.md
.
ExtensionPurposeWhere it goes
x-page-title
/
x-displayName
Display name of a tag (navigation + page title)tag
x-page-description
Short description shown above the page titletag
x-page-icon
Font Awesome icon for the pagetag
parent
/
x-parent
Nest a tag under a parent tag (
parent
= 3.2+,
x-parent
= 3.0.x/3.1.x)
tag
x-hideTryItPanel
Show or hide the "Test it" runnerroot or operation
x-expandAllResponses
Expand all response sections by defaultroot or operation
x-expandAllModelSections
Expand all model/schema sections by defaultroot or operation
x-enable-proxy
Route "Test it" requests through GitBook's proxyroot or operation (operation wins)
x-codeSamples
Provide custom code samples (
lang
,
label
,
source
)
operation
x-enumDescriptions
Per-value descriptions for an
enum
, rendered as a table
schema
x-internal
/
x-gitbook-ignore
Hide an endpoint from the referenceoperation
x-stability
Mark
experimental
,
alpha
, or
beta
operation
deprecated
Mark an operation deprecatedoperation
x-deprecated-sunset
Sunset date for a deprecated operation (
YYYY-MM-DD
)
operation
x-hideSample
Hide a single response sampleresponse object
x-gitbook-prefix
Custom auth prefix (e.g.
Token
); not allowed on
http
schemes
security scheme
x-gitbook-token-placeholder
Default token placeholder shown in the runnersecurity scheme
Two display extensions worth highlighting because they take a root default that operations can opt out of:
yaml
openapi: '3.0'
x-expandAllResponses: true        # default for every operation
x-expandAllModelSections: true
paths:
  /pets:
    get:
      x-expandAllResponses: false # opt this one out
Custom code samples replace GitBook's auto-generated snippets and accept multiple languages:
yaml
paths:
  /users:
    get:
      summary: Retrieve users
      x-codeSamples:
        - lang: JavaScript
          label: Node SDK
          source: |
            import { createAPIClient } from 'my-api-sdk';
            const client = createAPIClient({ apiKey: 'my-api-key' });
            client.users.list().then(console.log);
        - lang: cURL
          label: CLI
          source: |
            curl -L -H 'Authorization: Bearer <token>' \
              'https://api.example.com/v1/users'
一览 GitBook 支持的所有扩展。要查看任意条目的完整 YAML 示例,请打开
references/extensions.md
。
扩展用途作用位置
x-page-title
/
x-displayName
tag 的显示名称(导航和页面标题)tag
x-page-description
显示在页面标题上方的简短描述tag
x-page-icon
页面使用的 Font Awesome 图标tag
parent
/
x-parent
将 tag 嵌套在父 tag 下(
parent
= 3.2+,
x-parent
= 3.0.x/3.1.x)
tag
x-hideTryItPanel
显示或隐藏“Test it”运行器根级别或操作
x-expandAllResponses
默认展开所有响应区块根级别或操作
x-expandAllModelSections
默认展开所有 model/schema 区块根级别或操作
x-enable-proxy
通过 GitBook 的 proxy 路由“Test it”请求根级别或操作(操作级优先)
x-codeSamples
提供自定义代码示例(
lang
、
label
、
source
)
操作
x-enumDescriptions
为
enum
的每个值提供描述,并以表格形式呈现
schema
x-internal
/
x-gitbook-ignore
从参考文档中隐藏端点操作
x-stability
标记为
experimental
、
alpha
或
beta
操作
deprecated
将操作标记为已弃用操作
x-deprecated-sunset
已弃用操作的停用日期(
YYYY-MM-DD
)
操作
x-hideSample
隐藏单个响应示例响应对象
x-gitbook-prefix
自定义认证前缀(例如
Token
);不允许用于
http
方案
安全方案
x-gitbook-token-placeholder
运行器中显示的默认 token 占位符安全方案
有两个显示扩展尤其值得注意,因为它们提供根级默认值,而操作可以选择不采用:
yaml
openapi: '3.0'
x-expandAllResponses: true        # default for every operation
x-expandAllModelSections: true
paths:
  /pets:
    get:
      x-expandAllResponses: false # opt this one out
自定义代码示例会替换 GitBook 自动生成的代码片段,并支持多种语言:
yaml
paths:
  /users:
    get:
      summary: Retrieve users
      x-codeSamples:
        - lang: JavaScript
          label: Node SDK
          source: |
            import { createAPIClient } from 'my-api-sdk';
            const client = createAPIClient({ apiKey: 'my-api-key' });
            client.users.list().then(console.log);
        - lang: cURL
          label: CLI
          source: |
            curl -L -H 'Authorization: Bearer <token>' \
              'https://api.example.com/v1/users'

Automate with CI/CD

使用 CI/CD 自动化

Publish the spec from any pipeline with the CLI. Set
GITBOOK_TOKEN
as a secret, then run
openapi publish
against a file (generated during the build) or a URL (forces a refresh after a release).
bash
export GITBOOK_TOKEN=<api-token>
gitbook openapi publish \
  --spec <spec-name> \
  --organization <organization-id> \
  example.openapi.yaml
GitHub Actions example, triggered on spec changes to
main
:
yaml
name: Publish OpenAPI to GitBook
on:
  push:
    branches: ["main"]
    paths: ["**/*.yaml", "**/*.yml", "**/*.json"]
  workflow_dispatch:
jobs:
  publish:
    runs-on: ubuntu-latest
    env:
      GITBOOK_TOKEN: ${{ secrets.GITBOOK_TOKEN }}
      GITBOOK_SPEC_NAME: ${{ vars.GITBOOK_SPEC_NAME }}
      GITBOOK_ORGANIZATION_ID: ${{ vars.GITBOOK_ORGANIZATION_ID }}
    steps:
      - uses: actions/checkout@v4
      - name: Publish spec to GitBook
        run: |
          npx -y @gitbook/cli@latest openapi publish \
            --spec "$GITBOOK_SPEC_NAME" \
            --organization "$GITBOOK_ORGANIZATION_ID" \
            <path_to_spec>
可使用 CLI 从任意流水线发布规范。将
GITBOOK_TOKEN
设置为 secret,然后针对文件(构建期间生成)或 URL(发布后强制刷新)运行
openapi publish
。
bash
export GITBOOK_TOKEN=<api-token>
gitbook openapi publish \
  --spec <spec-name> \
  --organization <organization-id> \
  example.openapi.yaml
以下 GitHub Actions 示例会在规范变更并推送到
main
时触发:
yaml
name: Publish OpenAPI to GitBook
on:
  push:
    branches: ["main"]
    paths: ["**/*.yaml", "**/*.yml", "**/*.json"]
  workflow_dispatch:
jobs:
  publish:
    runs-on: ubuntu-latest
    env:
      GITBOOK_TOKEN: ${{ secrets.GITBOOK_TOKEN }}
      GITBOOK_SPEC_NAME: ${{ vars.GITBOOK_SPEC_NAME }}
      GITBOOK_ORGANIZATION_ID: ${{ vars.GITBOOK_ORGANIZATION_ID }}
    steps:
      - uses: actions/checkout@v4
      - name: Publish spec to GitBook
        run: |
          npx -y @gitbook/cli@latest openapi publish \
            --spec "$GITBOOK_SPEC_NAME" \
            --organization "$GITBOOK_ORGANIZATION_ID" \
            <path_to_spec>