> For the complete documentation index, see [llms.txt](https://docs.verge.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.verge.io/knowledge-base/zh/automation-api/verge-api-guide.md).

# API 指南

## 概述

VergeOS API 允许开发者以编程方式与 VergeOS 系统交互。它提供对系统操作的访问，例如创建虚拟机、管理资源，以及与计费和目录仓库交互。该 API 采用标准 REST 风格约定，并支持多种身份验证方法。本指南概述 VergeOS API、端点文档、示例请求和错误处理。

本文档概述了 API 的使用方式。有关 API 的详细信息可在 VergeOS UI 中作为 Swagger 文档页面找到，该页面会动态生成，并显示可用 API 表和操作的完整列表。

### Swagger 界面

要在 VergeOS UI 中访问 Swagger 文档：

1. **登录** 使用有效凭据登录 VergeOS 系统。
2. 选择 **系统** 从顶部菜单中。
3. 选择 **API Documentation**.
4. Swagger 文档页面将打开。此页面为每个 API 操作提供详细示例，并支持直接测试 API。

   ![Swagger 文档示例](/files/07e4ce1c472394a2c9b1b4eb9d1fe3eaef7b244a)
5. 选择一个单独的表，并选择可用的以下之一 **GET/POST/DELETE/PUT** 选项以查看并测试 API 操作。
6. 指定参数并点击 **执行按钮** 来运行 API 命令。这将返回响应，其中包括响应正文、标头和一个 curl 示例。

## API 基础

### HTTP 方法

VergeOS API 使用标准 HTTP 方法，如 GET、POST、PUT 和 DELETE 来操作资源。

### GET 参数

* **fields**：指定在结果集中返回哪些字段。
* **filter**：根据某些条件筛选结果集。
* **sort**：按指定字段对结果排序。
* **limit**：限制返回结果的数量。

### 身份验证

所有 API 请求都必须通过 HTTPS 发起，并且需要使用基本访问身份验证或会话令牌进行认证。

## 附加说明

* **速率限制**：该 API 每个 API 密钥每小时最多支持 1000 个请求。
* **数据格式**：所有响应都以 JSON 格式返回。
* **分页**：返回大量数据集的端点支持使用 `offset` 以及 `limit` 查询参数进行分页。

***

## 身份验证

VergeOS 支持两种身份验证方式：

1. **基本 HTTP 身份验证**\
   该 API 仅可通过 SSL 访问。
2. **基于令牌的身份验证**\
   开发者必须通过向以下端点发送 POST 请求来从 API 请求令牌： `/sys/tokens` 端点。随后将在后续 API 请求中通过 `x-yottabyte-token` 标头传递该令牌。

### 身份验证请求示例

要获取令牌：

```bash
curl --header "X-JSON-Non-Compact: 1" --basic --data-ascii '{"login": "USERNAME", "password": "PASSWORD"}' --insecure --request "POST" --header 'Content-Type: application/json' 'https://your-verge-instance.com/api/sys/tokens'
```

示例响应：

```json
{
   "location":"\\/sys\\/tokens\\/3a334563456378845634563b7b82d2efcadce9",
   "dbpath":"tokens\\/3a334563456378845634563b7b82d2efcadce9",
   "$row":1,
   "$key":"3a334563456378845634563b7b82d2efcadce9"
}
```

在后续所有请求中使用来自 `"$key"` 字段的令牌：

```bash
x-yottabyte-token: 3a334563456378845634563b7b82d2efcadce9
```

要注销，请向以下端点发送 DELETE 请求： `/sys/tokens/{token}` 端点。

### 注销请求示例

```bash
DELETE /sys/tokens/3a334563456378845634563b7b82d2efcadce9
```

***

### 虚拟机示例

该 **虚拟机** VergeOS API 的 VMs 部分允许用户以编程方式管理虚拟机。它包括用于列出、创建、修改和删除 VM 的端点。

### 检索虚拟机列表

**端点**:\
`GET /v4/vms?fields=most`

**说明**：检索系统中所有 VM 的列表，以及 CPU 核心、RAM、机器类型和配置详情等信息。

**示例请求**:

```bash
curl -X 'GET' \\
  'https://your-verge-instance.com/api/v4/vms?fields=most' \\
  -H 'accept: application/json' \\
  -H 'x-yottabyte-token: <your-token>'
```

**示例响应**:

```json
[
  {
    "$key": 1,
    "name": "CentOS 7 (Latest) 1.0-7",
    "machine": 7,
    "cpu_cores": 2,
    "cpu_type": "Cascadelake-Server",
    "ram": 2048,
    "os_family": "linux",
    "is_snapshot": true,
    "boot_order": "cd",
    "rtc_base": "utc",
    "console": "vnc",
    "uefi": false,
    "secure_boot": false,
    "serial_port": true,
    "uuid": "d3914756-4ec5-9dfe-5c45-b28af2fd3d73",
    "created": 1724435418,
    "modified": 1724435418
  }
]
```

**返回数据概览**:

* **$key**：VM 的唯一标识符。
* **name**：虚拟机的名称。
* **machine**：与 VM 关联的机器 ID。
* **cpu\_cores**：分配给 VM 的 CPU 核心数量。
* **ram**：分配的 RAM 数量（以 MB 为单位）。
* **os\_family**：操作系统类型。
* **uuid**：VM 的通用唯一标识符（UUID）。
* **created**：创建时间戳。
* **modified**：最后修改时间戳。

***

### 创建新的虚拟机

**端点**:\
`POST /v4/vms`

**说明**：创建一个新的虚拟机，具有特定的配置细节，例如 CPU 核心、RAM、机器类型、启动顺序等。

**示例请求**:

```bash
curl -X 'POST' \\
  'https://your-verge-instance.com/api/v4/vms' \\
  -H 'accept: application/json' \\
  -H 'x-yottabyte-token: <your-token>' \\
  -H 'Content-Type: application/json' \\
  -d '{
    "name": "rest",
    "description": "test",
    "machine_type": "pc-q35-9.0",
    "allow_hotplug": true,
    "cpu_cores": 1,
    "cpu_type": "Broadwell",
    "ram": 1024,
    "os_family": "linux",
    "boot_order": "cd",
    "uefi": false,
    "note": "test vm"
  }'
```

**示例响应**:

```json
{
  "location": "/v4/vms/36",
  "dbpath": "vms/36",
  "$row": 36,
  "$key": "36"
}
```

**返回数据概览**:

* **location**：新创建的 VM 资源位置。
* **dbpath**：新 VM 的数据库路径。
* **$row**：VM 的行 ID。
* **$key**：VM 的唯一键。

***

### 虚拟网络示例（Vnets）

该 **Vnets** VergeOS API 的 Vnets 部分允许用户以编程方式管理虚拟网络（Vnets）。它包括用于检索、创建和管理网络资源的端点，包括内部和外部网络，并支持速率限制等高级选项。

### 检索 Vnet 详情

**端点**:\
`GET /v4/vnets?fields=most`

**说明**：检索系统中所有 Vnets 的列表，以及网络类型、MTU、DHCP 设置和 DNS 配置等信息。

**示例请求**:

```bash
curl -X 'GET' \\
  'https://your-verge-instance.com/api/v4/vnets?fields=most' \\
  -H 'accept: application/json' \\
  -H 'x-yottabyte-token: <your-token>'
```

**示例响应**:

```json
[
  {
    "$key": 6,
    "name": "Internal Test 1",
    "advanced_options": {
      "dnsmasq": [
        "--dhcp-boot=netboot.xyz.kpxe,,192.168.10.20",
        "--dhcp-match=set:efi-x86,option:client-arch,6",
        "--dhcp-boot=tag:efi-x86,netboot.xyz.efi,,192.168.10.20",
        "--dhcp-match=set:efi-x86_64,option:client-arch,7",
        "--dhcp-boot=tag:efi-x86_64,netboot.xyz.efi,,192.168.10.20",
        "--dhcp-match=set:efi-x86_64,option:client-arch,9",
        "--dhcp-boot=tag:efi-x86_64,netboot.xyz.efi,,192.168.10.20"
      ]
    },
    "type": "internal",
    "layer2_type": "vxlan",
    "network": "192.168.100.0/24",
    "mtu": 9000,
    "dhcp_enabled": true,
    "dhcp_start": "192.168.100.100",
    "dhcp_stop": "192.168.100.200",
    "rate_limit": 0,
    "rate_limit_type": "mbytes/second",
    "gateway": ""
  }
]
```

**返回数据概览**:

* **$key**：Vnet 的唯一标识符。
* **name**：虚拟网络名称。
* **advanced\_options**：要传递给网络中运行服务的高级选项，在此示例中为 dnsmasq 的 netboot 标志
* **type**：网络类型（例如 internal）。
* **layer2\_type**：二层网络类型，例如 VXLAN。
* **network**：网络 CIDR 块。
* **mtu**：最大传输单元（MTU）大小。
* **dhcp\_enabled**：指示此网络是否启用 DHCP。
* **dhcp\_start**：DHCP 地址池的起始 IP 地址。
* **dhcp\_stop**：DHCP 地址池的结束 IP 地址。
* **rate\_limit**：网络速率限制（以 mbytes/second 为单位）。
* **gateway**：网络的默认网关。

***

### 创建带速率限制的内部网络

**端点**:\
`POST /v4/vnets`

**说明**：创建一个新的内部虚拟网络，带有速率限制和 DHCP 设置。

**示例请求**:

```bash
curl -X 'POST' \\
  'https://your-verge-instance.com/api/v4/vnets' \\
  -H 'accept: application/json' \\
  -H 'x-yottabyte-token: <your-token>' \\
  -H 'Content-Type: application/json' \\
  -d '{
    "name":"int1",
    "description":"workloads",
    "type":"internal",
    "mtu":"9000",
    "network":"192.168.80.0/24",
    "gateway":"192.168.80.1",
    "dnslist":"1.1.1.1",
    "dhcp_enabled": true,
    "rate_limit": 100,
    "rate_limit_burst": 500,
    "dhcp_start":"192.168.80.100",
    "dhcp_stop":"192.168.80.200"
  }'
```

**示例响应**:

```json
{
  "location": "/v4/vnets/8",
  "dbpath": "vnets/8",
  "$row": 8,
  "$key": "8"
}
```

**返回数据概览**:

* **location**：新创建的 Vnet 资源位置。
* **dbpath**：新 Vnet 的数据库路径。
* **$row**：Vnet 的行 ID。
* **$key**：Vnet 的唯一键。

***

## 资源

以下是用于查询机器列表的示例 URL。

*示例：<https://user1:xxxxxx@server1.verge.io/api/v4/machines?fields=all>*

|           |      |   |          |   |            |      |              |   |                                    |
| --------- | ---- | - | -------- | - | ---------- | ---- | ------------ | - | ---------------------------------- |
| https\:// | user | : | password | @ | server     | /api | /v4/machines | ? | filter=\&fields=all\&sort=\&limit= |
|           | 用户名  |   | 用户密码     |   | 服务器主机名或 IP |      | 资源位置（URI）    |   | 以下将对这些选项进行说明                       |

### GET 选项

#### 字段

* **指定在结果集中返回哪些字段（如果该表 schema 中定义了视图，也可以是一个视图）**.
* **all** 返回所有字段。
* **most** 返回大多数字段，但不包括参数字段和行。
* **summary** 返回在其 schema 中标记为 'summary' 的字段。
* 示例： `fields=name,email,enabled,groups[all] as all_groups,collapse(groups[name]) as first_groups_name`

字段函数：

* **collapse**
* **datetime**
* **upper**
* **lower**
* **count**
* **diskspace**
* **display**
* **hex**
* **sha1**
* **sum**
* **avg**
* **min**
* **max**

#### 筛选

* 按指定条件筛选结果集。
* 类似于 [OData](https://msdn.microsoft.com/en-us/library/gg309461\(v=crm.7\).aspx#BKMK_filter).
* 示例： `filter=enabled eq true and size gt 1048576`.
* 示例： `filter=cputype eq 'qemu' or cputype eq 'kvm'`.

| 运算符  | 说明           |
| ---- | ------------ |
| *eq* | 等于           |
| *ne* | 不等于          |
| *gt* | 大于           |
| *ge* | 大于或等于        |
| *lt* | 小于           |
| *le* | 小于或等于        |
| *bw* | 以...开头       |
| *ew* | 以...结尾       |
| *以及* | 逻辑与          |
| *或*  | 逻辑或          |
| *cs* | 包含字符串（区分大小写） |
| *ct* | 包含文本（不区分大小写） |
| *rx* | 正则匹配         |

#### 排序

* 按指定字段对结果排序。
* 示例： `sort=+name`.
* 示例： `sort=-id`.

#### 限制

* **limit** （整数）将结果集限制为指定数量的条目。值为 0 表示不受限制。
* 示例： `limit=1`.

### 通用 HTTP 响应状态码

* **400 - 错误请求**：请求无效。
* **401 - 登录失败 / 需要登录**：身份验证失败或需要身份验证。
* **403 - 权限被拒绝**：你缺少所需的权限。
* **404 - 未找到资源**：请求的行或 API 不存在。
* **405 - 不允许**：该操作不被允许。
* **409 - 行已存在**：该资源已存在。
* **422 - 验证失败 / 参数无效**：验证失败。
* **500 - 内部服务器错误**：发生了未处理的错误。

#### 仅适用于 POST

* **201 - 已创建**：已成功创建新行/资源。

#### 仅适用于 WebSocket（用于 VNC/SPICE）

* **101 - 切换协议**：协议已成功切换。

#### PUT/GET/DELETE

* **200 - 成功**：操作已成功完成。

***

### Schema 表定义

#### 字段类型

* **布尔**
* **文本**
* **字符串**
* **数值**
* **无符号8位整数**
* **无符号16位整数**
* **无符号32位整数**
* **无符号64位整数**
* **有符号8位整数**
* **有符号16位整数**
* **有符号32位整数**
* **有符号64位整数**
* **enabled**
* **created**
* **创建\_ms**
* **创建\_us**
* **modified**
* **修改\_ms**
* **修改\_us**
* **文件名**
* **文件大小**
* **文件已使用**
* **文件已分配**
* **文件已修改**
* **json**
* **行**
* **行**

#### 架构所有者 / 父字段

* **所有者字段**：如果所有者字段为空，则应用普通权限。如果所有者字段有值，则权限会被替换为对所有者的权限检查。
* **父字段**：权限检查应用于该行本身，如果权限检查失败，也会对父行进行权限检查。

***

### 完整表架构

要检索表的架构，请附加 **$table** 到 URI：

**/api/v4/machines/$table** （将“machines”替换为表名）。

系统会提示你输入凭据；这需要 VergeOS 管理员凭据。输出将采用 JSON 格式。Firefox 默认会以可读格式显示，而其他浏览器可能需要将 JSON 导出到外部程序以获得更好的可读性。

***

### 示例错误

#### 示例错误（HTTP 代码 422）

```json
{
  "err": "字段 'dhcp_start' 的验证错误 - '未通过验证测试'"
}
```

VergeOS 使用标准 HTTP 状态码来指示 API 请求的结果。

* **400 错误请求**：请求无效或无法处理。
* **401 未授权**：API 密钥缺失或无效。
* **403 禁止访问**：API 密钥缺少所需权限。
* **404 未找到**：资源不存在。
* **500 内部服务器错误**：发生服务器错误。

***

{% hint style="info" %}
**文档信息**

* 最后更新：2024-11-14
* vergeOS 版本：4.12.6
  {% endhint %}


---

# 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 dynamically by asking a question.

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

```
GET https://docs.verge.io/knowledge-base/zh/automation-api/verge-api-guide.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
