# OpenAPI

手动编写 REST API 文档可能是一个耗时的过程。幸运的是，GitBook 允许你导入 OpenAPI 文档，从而简化了这项任务；这些文档会详细说明你的 API 结构和功能。

OpenAPI 规范（OAS）是开发者用来记录 REST API 的一个框架。它使用 JSON 或 YAML 编写，概述了你的所有端点、参数、模式和认证方案。

导入到 GitBook 后，这些文档会被转换为可交互、可测试的 API 块，以可视化方式呈现你的 API 方法——无论规范是作为文件提供还是从 URL 加载。

GitBook 支持 [Swagger 2.0](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md) 或 [OpenAPI 3.0](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md) 符合规范的文件。

{% openapi src="<https://petstore3.swagger.io/api/v3/openapi.json>" path="/pet" method="post" %}
<https://petstore3.swagger.io/api/v3/openapi.json>
{% endopenapi %}

### 测试它（由 Scalar 提供）

GitBook 的 OpenAPI 块还支持“测试它”功能，允许你的用户使用编辑器中填充的数据和参数来测试你的 API 方法。

由 [Scalar](https://scalar.com/)，你无需离开文档就能查看你的 API 方法实际运行的效果。上面有一个示例。

#### 常见问题

<details>

<summary>为什么我的规范没有加载？</summary>

{% hint style="info" %}
**注意：** 此信息仅适用于 **通过 URL 添加的规范**.
{% endhint %}

如果你是通过 URL 添加你的规范，你的 API 必须 [允许跨源](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Origin) 来自你文档站点的 GET 请求。在你的 API 的 CORS 设置中，允许文档托管所在的确切源（例如， `https://your-site.gitbook.io` 或 `https://docs.example.com`）。\
\
如果你的端点是公开的且不使用凭据，你也可以返回： `Access-Control-Allow-Origin: *`\ <br>

</details>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gitbook.com/docs/documentation/zh/api-references/openapi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
