# HTTP Client

> 发起 HTTP 请求。

Source: https://docs.sommatic.ai/zh/nodes/io.http/

- 标识: `io.http`
- 类别: 输入与输出
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

发起 HTTP 请求。

## 配置

- `connection_id` (string, 可选): HTTP 请求的可选凭据。接受 `api-key`、`basic-auth`、`oauth2` 或 `object`（自定义请求头/认证）类型的凭据。
- `url` (string, 必填, 支持表达式): 完整 URL；使用连接时可填路径。
- `method` (string, 可选): 默认值: `GET`. 可选值: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`.
- `headers` (object, 可选, 支持表达式): 以键值对表示的 HTTP 请求头。
- `body` (object, 可选, 支持表达式): JSON 请求体。支持 {{expressions}}。

支持通用执行设置：重试（`retryOnFail`、`maxTries`、`waitBetweenTries`）与超时。

## 输出端口

- `out` (默认): 成功的 HTTP 响应（2xx）
- `error`: HTTP client_error（4xx）或 server_error（5xx）

## 输入契约

- `connection_id` (string, 可选)
- `url` (string, 必填)
- `method` (string, 可选)
- `headers` (object, 可选)
- `body` (object, 可选)

## 输出契约

- `status` (number, 可选)
- `headers` (object, 可选)
- `data` (object, 可选): 响应正文

## 在表达式中

后续节点可通过 `$("HTTP Client").item.json.<路径>` 读取此节点输出中的内容（请把 `HTTP Client` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `out` 返回的路径，依据“端口”一节所示的输出。

- `$("HTTP Client").item.json.status` (number) = `200`
- `$("HTTP Client").item.json.headers` (object) = `{…}`
- `$("HTTP Client").item.json.data` (object) = `{…}`: 响应正文
- `$("HTTP Client").item.json.data.id` (string) = `"ord_123"` (编辑器不提示)
- `$("HTTP Client").item.json.data.status` (string) = `"paid"` (编辑器不提示)
- `$("HTTP Client").item.json.headers.content-type` (string) = `"application/json; charset=utf-8"` (编辑器不提示)


## 工作原理

发送一次 HTTP 请求，可选使用在服务器端解析的凭据进行认证；对限流、5xx 和瞬时网络故障按指数退避重试。

1. 解析配置：`url`、`headers` 和 `body` 中的表达式会基于当前运行求值。
2. 设置 `connection_id` 时解析凭据：若 `url` 不以 `http` 开头则加上 `config.baseUrl` 前缀，并根据密钥添加一个认证头，按顺序首个匹配生效：`token` → `Authorization: Bearer`，`username` + `password` → `Authorization: Basic`，`apiKey` → 请求头 `config.headerName`（默认 `x-api-key`）。
3. 计算重试策略（见 `http_retry_*` 和 `execution`）。
4. 通过 IPv4 向 `url` 发送 `method` 请求，携带 `headers`，并以 `body` 作为请求数据。客户端接受所有状态码，由 worker 进行分类。
5. 2xx 以 `{ status, data, headers }` 从 `out` 输出。429 和 5xx 在仍有剩余次数时重试，瞬时网络错误同样重试；其他情况立即从 `error` 输出。

## 在工作流中

### 节点

```json
{
  "node_id": "node-call-erp",
  "label": "Call ERP",
  "operator_slug": "io.http",
  "operator_version": "1.0.0",
  "config": {
    "url": "https://api.example.com/orders/{{ $json.order_id }}",
    "method": "GET",
    "headers": {
      "accept": "application/json"
    },
    "connection_id": "pi-credential-xxxx",
    "http_retry_max_attempts": 3,
    "http_retry_backoff_ms": 1000
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "status": 200,
    "data": {
      "id": "ord_123",
      "status": "paid"
    },
    "headers": {
      "content-type": "application/json; charset=utf-8"
    }
  },
  "port": "out"
}
```

## 输出端口 (代码中的行为)

### `out`

服务器返回 2xx 状态。`data` 为解析后的响应正文（服务器返回 JSON 时为 JSON，否则为文本）。

```json
{
  "status": 200,
  "data": {
    "id": "ord_123",
    "status": "paid"
  },
  "headers": {
    "content-type": "application/json; charset=utf-8"
  }
}
```

### `error`

最后一次尝试后仍为非 2xx 状态（数据为 `{ status, data, message }`），或出现网络/准备阶段故障（数据为 `{ error, response }`）。

```json
{
  "status": 404,
  "data": {
    "message": "Order not found"
  },
  "message": "HTTP Request Failed with status 404"
}
```

## 代码中的行为

- `http_retry_max_attempts`: 未在 schema 中声明。总尝试次数（含首次），优先于 `execution`。小于 1 或非数字时取 1，上限为 5。
- `http_retry_backoff_ms`: 未声明。基础等待时间（毫秒），缺失时依次回退到 `execution.waitBetweenTries` 和 1000。第 n 次重试前的等待为 `base × 2^(n−1)` 加 0–249 毫秒随机抖动，上限为 `http_retry_max_wait_ms`。
- `http_retry_max_wait_ms`: 未声明。单次等待的上限，默认 20000，最大不超过 30000。
- `execution`: 仅在缺少 `http_retry_max_attempts` 时使用：`retryOnFail: false` 时只尝试 1 次；否则尝试 `maxTries` 次（默认 3）。没有 `execution` 块时，节点最多尝试 3 次。此 worker 不应用 `timeout_ms`、`continueOnFail` 和 `alwaysOutputData`。
- `method`: 为空时按 GET 发送请求。
- `connection_id`: 密钥必须是包含 `token`、`username` + `password` 或 `apiKey` 的对象，例如 `basic-auth`、`oauth2` 或 `object` 凭据。以纯字符串保存的 `api-key` 凭据不会添加任何请求头。`config.baseUrl` 和 `config.headerName` 取自凭据配置。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `HTTP Request Failed with status <status>` | `error` | 服务器返回非 2xx 状态。除 429 外的 4xx 从不重试；429 和 5xx 仅在最后一次尝试后才到达此端口。`data` 中包含响应正文。 |
| `<network error message>` | `error` | 每次尝试连接均失败（例如 `connect ETIMEDOUT`、`getaddrinfo ENOTFOUND`），或出现非瞬时错误。请检查 URL，并确认编排器可以访问该主机。 |
| `Failed to resolve connection <connection_id>: <detail>` | `error` | 凭据不存在或此工作流无权使用。不会重试。 |

## 说明与限制

- 会重试的状态码：429 和 500–599。会重试的网络错误：`ETIMEDOUT`、`ECONNRESET`、`ECONNREFUSED`、`ECONNABORTED`、`ENOTFOUND`、`EAI_AGAIN`、`EPIPE`、`ENETUNREACH`、`EHOSTUNREACH`，以及消息中包含 “timeout” 的任何错误。
- 重试会重新发送同一请求：请确保非幂等调用（POST、PATCH）可安全重复，或设置 `http_retry_max_attempts: 1`。
- 请求本身没有超时设置；服务器一直不响应时，节点会持续等待。
- 连接强制使用 IPv4，且不会在运行之间保持。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "io.http",
  "name": "HTTP Client",
  "category": "io",
  "version": "1.0.0",
  "description": "Make HTTP Requests.",
  "capabilities": [
    "http",
    "api",
    "rest"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string",
        "title": "HTTP Credential (optional)",
        "description": "Optional credential for the HTTP request. Accepts credentials of type `api-key`, `basic-auth`, `oauth2`, or `object` (custom headers / auth).",
        "ui_widget": "connection_picker",
        "ui_options": {
          "credential_types": [
            "api-key",
            "basic-auth",
            "oauth2",
            "object"
          ],
          "types": [
            "http"
          ]
        }
      },
      "url": {
        "type": "string",
        "title": "URL",
        "description": "Full URL or Path if connection used.",
        "format": "expression"
      },
      "method": {
        "type": "string",
        "title": "Method",
        "enum": [
          "GET",
          "POST",
          "PUT",
          "PATCH",
          "DELETE"
        ],
        "default": "GET"
      },
      "headers": {
        "type": "object",
        "title": "Headers",
        "description": "HTTP headers as key-value pairs.",
        "format": "expression"
      },
      "body": {
        "type": "object",
        "title": "Body",
        "description": "JSON body. Supports {{expressions}}.",
        "format": "expression"
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    },
    "required": [
      "url"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string"
      },
      "url": {
        "type": "string"
      },
      "method": {
        "type": "string"
      },
      "headers": {
        "type": "object"
      },
      "body": {
        "type": "object"
      }
    },
    "required": [
      "url"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "status": {
        "type": "number"
      },
      "headers": {
        "type": "object"
      },
      "data": {
        "type": "object",
        "description": "Response Body"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Response",
      "description": "Successful HTTP response (2xx)",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "HTTP client_error (4xx) or server_error (5xx)",
      "is_default": false,
      "supports_condition": true
    }
  ],
  "execution_mode": "async",
  "required_resources": [],
  "compatible_worker_pools": [
    "standard-io",
    "high-throughput-io"
  ],
  "tags": [
    "api",
    "rest"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_link_loom",
    "profile": {
      "name": "Link Loom",
      "verified": true,
      "url": "https://me.veripass.com/link-loom",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string",
      "title": "HTTP Credential (optional)",
      "description": "Optional credential for the HTTP request. Accepts credentials of type `api-key`, `basic-auth`, `oauth2`, or `object` (custom headers / auth).",
      "ui_widget": "connection_picker",
      "ui_options": {
        "credential_types": [
          "api-key",
          "basic-auth",
          "oauth2",
          "object"
        ],
        "types": [
          "http"
        ]
      }
    },
    "url": {
      "type": "string",
      "title": "URL",
      "description": "Full URL or Path if connection used.",
      "format": "expression"
    },
    "method": {
      "type": "string",
      "title": "Method",
      "enum": [
        "GET",
        "POST",
        "PUT",
        "PATCH",
        "DELETE"
      ],
      "default": "GET"
    },
    "headers": {
      "type": "object",
      "title": "Headers",
      "description": "HTTP headers as key-value pairs.",
      "format": "expression"
    },
    "body": {
      "type": "object",
      "title": "Body",
      "description": "JSON body. Supports {{expressions}}.",
      "format": "expression"
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  },
  "required": [
    "url"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string"
    },
    "url": {
      "type": "string"
    },
    "method": {
      "type": "string"
    },
    "headers": {
      "type": "object"
    },
    "body": {
      "type": "object"
    }
  },
  "required": [
    "url"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "status": {
      "type": "number"
    },
    "headers": {
      "type": "object"
    },
    "data": {
      "type": "object",
      "description": "Response Body"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Response",
    "description": "Successful HTTP response (2xx)",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "HTTP client_error (4xx) or server_error (5xx)",
    "is_default": false,
    "supports_condition": true
  }
]
```
