> For the complete documentation index, see [llms.txt](https://docs.goassay.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.goassay.ai/developers/zh/shang-jia-ni-de-api-jin-jie/map-your-api.md).

# 将你的 API 映射到工具契约

将工具输入和输出转换为 API 现有的请求和响应格式。

工具契约描述客户提供的参数和收到的结果。其 `inputSchema` 和 `outputSchema` 定义 JSON 字段及类型。如果 API 使用不同的名称、嵌套结构或请求参数，请使用映射。

## 工作原理

Assay 按 `inputSchema` 检查工具输入，再映射为 HTTP 请求。随后调用 API、对响应分类、映射返回的 JSON，并按 `outputSchema` 检查映射结果。响应映射读取的是响应体，不是含 HTTP 状态和响应头的封装对象。

| 方向 | 读取来源           | 写入目标                                       |
| -- | -------------- | ------------------------------------------ |
| 请求 | 工具参数           | 方法（`GET` 或 `POST`）、附加路径、查询参数、请求头和 JSON 请求体 |
| 响应 | API 的 JSON 响应体 | 工具输出字段                                     |

映射会重组数据并应用指定转换，不会运行自定义代码。请将凭据保存在 **Add headers**，不要放入映射。

## 示例

假设工具接受 `{"city":"Hanoi"}`，并承诺返回数值型 `temperatureC`。API 接受 `location` 查询参数，返回 `{"weather":{"temp_c":"27.5"}}`。

将 **Your API's address** 设为 `https://api.example.com`，并使用此请求映射：

```json
{
  "method": "GET",
  "path": "/weather",
  "query": {
    "location": { "$path": "$.city" },
    "units": { "$const": "metric" }
  }
}
```

使用此响应映射：

```json
{
  "temperatureC": {
    "$path": "$.weather.temp_c",
    "$transform": ["toNumber"]
  }
}
```

请求会调用 `/weather`，并附带 `location=Hanoi` 和 `units=metric`。映射结果为 `{"temperatureC":27.5}`。这些名称仅为示例：请使用所选契约和实际 API 响应中的字段。

## 保存并测试映射

1. 打开上架条目的 **Connect & test** 步骤。设置端点的 **Your API's address** 和身份认证。
2. 在 **How we call your API** 下打开 **Advanced mapping**。
3. 编辑 **How a call reaches your API** 和 **How your answer becomes the result**。开启 **Edit as JSON**，即可粘贴相应映射对象。
4. 输入有效工具参数，点击 **Save and run test**。
5. 对照生成的请求、原始响应、映射结果和验证结果。先修复第一个失败的层级，再重新测试。

测试器会真实调用 API。它使用上架条目的超时设置，但最多 30 秒。后续标为 `NOT_REACHED` 的层级尚未检查。`INCONCLUSIVE` 也不代表通过。如果未保存验证策略，测试器只使用工具 schema，并将结果标为 `TOOL_SCHEMA_ONLY`。

## 确认是否成功

除了绿色结果，也要核对映射后的值。尝试有代表性的输入，包括空响应和可选字段。修改调用或映射后，请重新运行测试器。发布前，每个提供服务的契约主版本都需要通过测试。

## 详情

| 映射节点                                                          | 行为                                                                   |
| ------------------------------------------------------------- | -------------------------------------------------------------------- |
| `{"$path":"$.city"}`                                          | 从源文档读取字段。路径不存在时会失败，除非提供默认值或标为可选。                                     |
| `{"$const":"metric"}`                                         | 写入字面值。                                                               |
| `$default`                                                    | 路径不存在时提供值。默认不会替换显式的 `null`。                                          |
| `$optional: true`                                             | 省略不存在的字段。不会免除契约要求的必填输出。                                              |
| `$onNull`                                                     | 默认为 `PASS`；`DEFAULT` 使用 `$default`；`ERROR` 拒绝空值。                     |
| `$transform`                                                  | 按顺序应用指定转换，如 `toNumber` 或 `epochSecondsToIso`。                        |
| `{"$from":"$.items[*]","$item":{"title":{"$path":"$.name"}}}` | 映射每个选中项；`$item` 内的选择器读取该项。`$onEmpty` 默认为 `PASS`（`[]`）；`ERROR` 拒绝空集合。 |

`/cities/{$.cityId}` 这类路径模板会将选中的标量编码为路径段。查询参数和请求头值必须是标量，并会转为字符串。对象、数组和空值必须先明确转换，才能放入这些位置。不要在映射的附加路径中重复端点路径前缀。

<details>

<summary>可选：了解缺失字段的归因</summary>

响应选择器未选中任何内容，通常表示映射缺陷，归因于平台。选择到的值类型错误，则表示提供方数据有误。这一区分是分类依据，不会自动触发罚没。

如果你明确承诺提供某个可选输出，它对你的上架条目就成为必填项。如果缺失或为空，即使基础契约将其列为可选，Assay 也会视为提供方违背承诺。

</details>

## 错误

| 不匹配情况                                 | 解决方法                                 |
| ------------------------------------- | ------------------------------------ |
| `TOOL_MAPPING_PATH_NOT_FOUND`         | 对照实际 JSON 嵌套结构和拼写，检查选择器。             |
| `TOOL_MAPPING_TYPE_MISMATCH`          | 匹配 schema 类型；只在保留原意时使用转换。            |
| `TOOL_MAPPING_NULL_VALUE`             | 决定空值是否有效、是否应使用默认值，或是否必须失败。           |
| `TOOL_MAPPING_REQUIRED_FIELD_MISSING` | 提供必填输入或输出，包括你承诺提供的输出。                |
| `TOOL_MAPPING_EMPTY_COLLECTION`       | 检查选择器，以及契约是否允许空响应。                   |
| HTTP 成功，但分类或验证失败                      | HTTP 状态成功本身不能证明返回数据符合契约。请阅读第一个失败的层级。 |

## 延伸阅读

* [API 密钥还是签名](/developers/zh/shang-jia-ni-de-api-ru-men/api-key-or-signature.md)。
* 上架你的 API（可选）：[映射你的 API](https://docs.goassay.ai/list-your-api/zh/list-a-catalogue-tool)。

## 下一步

* [在生产环境运行验证](/developers/zh/shang-jia-ni-de-api-jin-jie/run-in-production.md)。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.goassay.ai/developers/zh/shang-jia-ni-de-api-jin-jie/map-your-api.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
