en	# 20 API
zh-cn	# 19. API

en	### Overview The Zabbix API allows you to programmatically retrieve and modify configuration of Zabbix and provides access to historical data. It is widely used to: - create new applications to work with Zabbix; - integrate Zabbix into a third-party software; - automate routine tasks. The Zabbix API is an HTTP-based API, and it is shipped as a part of the web frontend. It uses the JSON-RPC 2.0 protocol, which means two things: - the API consists of a set of separate methods; - requests and responses between the clients and the API are encoded using the JSON format. For more information about the protocol and JSON, see the [JSON-RPC 2.0 specification](http://www.jsonrpc.org/specification) and the [JSON format homepage](http://json.org/). For more information about integrating Zabbix functionality into your Python applications, see the [zabbix_utils](https://github.com/zabbix/python-zabbix-utils) Python library for Zabbix API.
zh-cn	### 概览 Zabbix API 允许您以编程方式检索和修改 Zabbix 的配置，并提供对历史数据的访问。 它被广泛用于： - 创建新的应用程序与 Zabbix 一起工作； - 将 Zabbix 集成到第三方软件中； - 自动化日常任务。 Zabbix API 是基于 HTTP 的 API，它作为 web 前端的一部分提供。 它使用 JSON-RPC 2.0 协议，这意味着两件事： - API 由一组独立的方法组成； - 客户端和 API 之间的请求和响应使用 JSON 格式编码。 有关协议和 JSON 的更多信息，请参见 [JSON-RPC 2.0 规范](http://www.jsonrpc.org/specification) 和 [JSON 格式主页](http://json.org/)。 有关将 Zabbix 功能集成到您的 Python 应用程序中的更多信息，请参见 [zabbix_utils](https://github.com/zabbix/python-zabbix-utils) Python 库，用于 Zabbix API。

en	### Structure The API consists of a number of methods that are nominally grouped into separate APIs. Each of the methods performs one specific task. For example, the `host.create` method belongs to the *host* API and is used to create new hosts. Historically, APIs are sometimes referred to as "classes". ::: notetip Most APIs contain at least four methods: `get`, `create`, `update` and `delete` for retrieving, creating, updating and deleting data respectively, but some APIs may provide a totally different set of methods. :::
zh-cn	### 结构 API 由许多方法组成，这些方法名义上被分组到不同的 API 中。每种方法执行一个特定任务。例如，`host.create` 方法属于 *host* API，用于创建新的主机。从历史上看，API 有时被称为 "类"。 ::: notetip 大多数 API 至少包含四种方法：`get`、`create`、`update` 和 `delete`，分别用于获取、创建、更新和删除数据，但有些 API 可能提供完全不同的方法集。 :::

en	### Performing requests Once you have set up the frontend, you can use remote HTTP requests to call the API. To do that, you need to send HTTP POST requests to the `api_jsonrpc.php` file located in the frontend directory. For example, if your Zabbix frontend is installed under `https://example.com/zabbix`, an HTTP request to call the `apiinfo.version` method may look like this: ```bash curl --request POST \ --url 'https://example.com/zabbix/api_jsonrpc.php' \ --header 'Content-Type: application/json-rpc' \ --data '{"jsonrpc":"2.0","method":"apiinfo.version","params":{},"id":1}' ``` The request must have the `Content-Type` header set to one of these values: `application/json-rpc`, `application/json` or `application/jsonrequest`. The request object must contain the following properties: - `jsonrpc` - the version of the JSON-RPC protocol used by the API (Zabbix API implements JSON-RPC version 2.0); - `method` - the API method being called; - `params` - the parameters that will be passed to the API method; - `id` - an arbitrary identifier of the request (if omitted, the API treats the request as a [notification](https://www.jsonrpc.org/specification#notification)). If the request is correct, the response returned by the API should look like this: ```json { "jsonrpc": "2.0", "result": "7.4.0", "id": 1 } ``` The response object, in turn, contains the following properties: - `jsonrpc` - the version of the JSON-RPC protocol; - `result` - the data returned by the method; - `id` - an identifier of the corresponding request.
zh-cn	### 执行请求 一旦您设置了前端，就可以使用远程 HTTP 请求来调用 API。为此，您需要发送 HTTP POST 请求到前端目录中的 `api_jsonrpc.php` 文件。例如，如果您的 Zabbix 前端安装在 `https://example.com/zabbix` 下，调用 `apiinfo.version` 方法的 HTTP 请求可能看起来像这样： ::: ```bash curl --request POST \ --url 'https://example.com/zabbix/api_jsonrpc.php' \ --header 'Content-Type: application/json-rpc' \ --data '{"jsonrpc":"2.0","method":"apiinfo.version","params":{},"id":1}' ``` 请求必须将 `Content-Type` 头部设置为以下值之一：`application/json-rpc`、`application/json` 或 `application/jsonrequest`。 请求对象包含以下属性： - `jsonrpc` - API 使用的 JSON-RPC 协议版本（Zabbix API 实现了 JSON-RPC 版本 2.0）； - `method` - 正在调用的 API 方法； - `params` - 将传递给 API 方法的参数； - `id` - 请求的任意标识符。 如果请求正确，API 返回的响应应该像这样： ```json { "jsonrpc": "2.0", "result": "7.0.0", "id": 1 } ``` 返回的响应对象，包含以下属性： - `jsonrpc` - JSON-RPC 协议的版本； - `result` - 方法返回的数据； - `id` - 对应请求的标识符。

en	### Example workflow The following section will walk you through some examples of usage in a greater detail.
zh-cn	### 示例工作流程 接下来的部分将以更详细的示例指导您了解使用方法。

en	#### Authentication To access any data in Zabbix, you need to either: - use an existing [API token](/manual/web_interface/frontend_sections/users/api_tokens) (created in Zabbix frontend or using the [Token API](/manual/api/reference/token)); - use an authentication token obtained with the [user.login](/manual/api/reference/user/login) method. For example, if you wanted to obtain a new authentication token by logging in as a standard *Admin* user, then a JSON request would look like this: ```bash curl --request POST \ --url 'https://example.com/zabbix/api_jsonrpc.php' \ --header 'Content-Type: application/json-rpc' \ --data '{"jsonrpc":"2.0","method":"user.login","params":{"username":"Admin","password":"zabbix"},"id":1}' ``` If you provided the credentials correctly, the response returned by the API should contain the user authentication token: ```json { "jsonrpc": "2.0", "result": "0424bd59b807674191e7d77572075f33", "id": 1 } ```
zh-cn	#### 认证 要在 Zabbix 中访问任何数据，您需要： - 使用现有的 [API token](/manual/web_interface/frontend_sections/users/api_tokens)（在 Zabbix 前端创建或使用 [Token API](/manual/api/reference/token) 创建）； - 使用通过 [user.login](/manual/api/reference/user/login) 方法获得的认证令牌。 例如，如果您想以标准 *Admin* 用户身份登录以获取新的认证令牌，那么一个 JSON 请求可能看起来像这样： ```bash curl --request POST \ --url 'https://example.com/zabbix/api_jsonrpc.php' \ --header 'Content-Type: application/json-rpc' \ --data '{"jsonrpc":"2.0","method":"user.login","params":{"username":"Admin","password":"zabbix"},"id":1}' ``` 如果您正确提供了凭据，API 返回的响应应该包含用户认证令牌： ```json { "jsonrpc": "2.0", "result": "0424bd59b807674191e7d77572075f33", "id": 1 } ```

en	#### Authorization methods
zh-cn	#### 授权方法

en	##### By "Authorization" header All API requests require an authentication or an API token. You can provide the credentials by using the Authorization header in the request: ```bash curl --request POST \ --url 'https://example.com/zabbix/api_jsonrpc.php' \ --header 'Authorization: Bearer 0424bd59b807674191e7d77572075f33' ``` ::: noteimportant If you are experiencing authentication issues, see [Authorization header forwarding](/manual/installation/known_issues#authorization-header-forwarding). ::: Zabbix API accepts headers in a case-insensitive way (e.g., `authorization`, `Authorization`, and `AUTHORIZATION` are treated the same). The Authorization header is supported in cross-origin requests ([CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)).
zh-cn	##### 通过 "Authorization" 头部 所有 API 请求都需要认证或 API 令牌。 您可以使用 "Authorization" 请求头部提供凭据： ```bash curl --request POST \ --url 'https://example.com/zabbix/api_jsonrpc.php' \ --header 'Authorization: Bearer 0424bd59b807674191e7d77572075f33' ```

en	##### By Zabbix cookie A *"zbx_session"* cookie is used to authorize an API request from Zabbix UI performed using JavaScript (from a module or a custom widget).
zh-cn	##### 通过 Zabbix cookie 一个 *"zbx_session"* cookie 被用来授权通过 JavaScript（来自模块或自定义控件）执行的来自 Zabbix UI 的 API 请求。

en	#### Retrieving hosts Now you have a valid user authentication token that can be used to access the data in Zabbix. For example, you can use the [host.get](/manual/api/reference/host/get) method to retrieve the IDs, host names and interfaces of all the configured [hosts](/manual/api/reference/host/object): Request: ```bash curl --request POST \ --url 'https://example.com/zabbix/api_jsonrpc.php' \ --header 'Authorization: Bearer ${AUTHORIZATION_TOKEN}' \ --header 'Content-Type: application/json-rpc' \ --data @data.json ``` ::: notetip `data.json` is a file that contains a JSON query. Instead of a file, you can pass the query in the `--data` argument. ::: data.json ```json { "jsonrpc": "2.0", "method": "host.get", "params": { "output": [ "hostid", "host" ], "selectInterfaces": [ "interfaceid", "ip" ] }, "id": 2 } ``` The response object will contain the requested data about the hosts: ```json { "jsonrpc": "2.0", "result": [ { "hostid": "10084", "host": "Zabbix server", "interfaces": [ { "interfaceid": "1", "ip": "127.0.0.1" } ] } ], "id": 2 } ``` ::: notetip For performance reasons it is always recommended to list the object properties you want to retrieve. Thus, you will avoid retrieving everything. :::
zh-cn	#### 获取主机 现在您有一个有效的用户认证令牌，可以用来访问 Zabbix 中的数据。例如，您可以使用 [host.get](/manual/api/reference/host/get) 方法来检索所有配置的 [hosts](/manual/api/reference/host/object) 的 ID、主机名和接口： 请求： ```bash curl --request POST \ --url 'https://example.com/zabbix/api_jsonrpc.php' \ --header 'Authorization: Bearer ${AUTHORIZATION_TOKEN}' \ --header 'Content-Type: application/json-rpc' \ --data @data.json ``` ::: notetip `data.json` 是一个包含 JSON 查询的文件。您可以在 `--data` 参数中直接传递查询，而不是使用文件。 ::: data.json ```json { "jsonrpc": "2.0", "method": "host.get", "params": { "output": [ "hostid", "host" ], "selectInterfaces": [ "interfaceid", "ip" ] }, "id": 2 } ``` 响应对象将包含有关主机的请求数据： ```json { "jsonrpc": "2.0", "result": [ { "hostid": "10084", "host": "Zabbix server", "interfaces": [ { "interfaceid": "1", "ip": "127.0.0.1" } ] } ], "id": 2 } ``` ::: notetip 出于性能考虑，始终建议列出您想要检索的对象属性。这样，您将避免检索所有内容。 :::

en	#### Creating a new item Now, create a new [item](/manual/api/reference/item/object) on the host "Zabbix server" using the data you have obtained from the previous `host.get` request. This can be done using the [item.create](/manual/api/reference/item/create) method: ```bash curl --request POST \ --url 'https://example.com/zabbix/api_jsonrpc.php' \ --header 'Authorization: Bearer ${AUTHORIZATION_TOKEN}' \ --header 'Content-Type: application/json-rpc' \ --data '{"jsonrpc":"2.0","method":"item.create","params":{"name":"Free disk space on /home/joe/","key_":"vfs.fs.size[/home/joe/,free]","hostid":"10084","type":0,"value_type":3,"interfaceid":"1","delay":30},"id":3}' ``` A successful response will contain the ID of the newly created item, which can be used to reference the item in the following requests: ```json { "jsonrpc": "2.0", "result": { "itemids": [ "24759" ] }, "id": 3 } ``` ::: notetip The `item.create` method as well as other *create methods* can also accept arrays of objects and create multiple items with one API call. :::
zh-cn	#### 创建新监控项 现在，在主机 "Zabbix server" 上使用您从上一个 `host.get` 请求获得的数据创建一个新的 [item](/manual/api/reference/item/object)。这可以通过使用 [item.create](/manual/api/reference/item/create) 方法来完成： ```bash curl --request POST \ --url 'https://example.com/zabbix/api_jsonrpc.php' \ --header 'Authorization: Bearer ${AUTHORIZATION_TOKEN}' \ --header 'Content-Type: application/json-rpc' \ --data '{"jsonrpc":"2.0","method":"item.create","params":{"name":"Free disk space on /home/joe/","key_":"vfs.fs.size[/home/joe/,free]","hostid":"10084","type":0,"value_type":3,"interfaceid":"1","delay":30},"id":3}' ``` 成功的响应将包含新创建监控项的 ID，该 ID 可用于在随后的请求中引用该监控项： ```json { "jsonrpc": "2.0", "result": { "itemids": [ "24759" ] }, "id": 3 } ``` ::: notetip `item.create` 方法以及其他 *创建方法* 也可以接受对象数组，并用一个 API 调用创建多个监控项。 :::

en	#### Creating multiple triggers Thus, if *create methods* accept arrays, you can add multiple [triggers](/manual/api/reference/trigger/object), for example, this one: ```bash curl --request POST \ --url 'https://example.com/zabbix/api_jsonrpc.php' \ --header 'Authorization: Bearer ${AUTHORIZATION_TOKEN}' \ --header 'Content-Type: application/json-rpc' \ --data '{"jsonrpc":"2.0","method":"trigger.create","params":[{"description":"Processor load is too high on {HOST.NAME}","expression":"last(/Linux server/system.cpu.load[percpu,avg1])>5",},{"description":"Too many processes on {HOST.NAME}","expression":"avg(/Linux server/proc.num[],5m)>300",}],"id":4}' ``` The successful response will contain the IDs of the newly created triggers: ```json { "jsonrpc": "2.0", "result": { "triggerids": [ "17369", "17370" ] }, "id": 4 } ```
zh-cn	#### 创建多个触发器 因此，如果 *创建方法* 接受数组，您可以添加多个 [触发器](/manual/api/reference/trigger/object)，例如： ```bash curl --request POST \ --url 'https://example.com/zabbix/api_jsonrpc.php' \ --header 'Authorization: Bearer ${AUTHORIZATION_TOKEN}' \ --header 'Content-Type: application/json-rpc' \ --data '{"jsonrpc":"2.0","method":"trigger.create","params":[{"description":"Processor load is too high on {HOST.NAME}","expression":"last(/Linux server/system.cpu.load[percpu,avg1])>5",},{"description":"Too many processes on {HOST.NAME}","expression":"avg(/Linux server/proc.num[],5m)>300",}],"id":4}' ``` 成功的响应将包含新创建的触发器的 ID： ```json { "jsonrpc": "2.0", "result": { "triggerids": [ "17369", "17370" ] }, "id": 4 } ```

en	#### Updating an item Enable an item by setting its status to "0": ```bash curl --request POST \ --url 'https://example.com/zabbix/api_jsonrpc.php' \ --header 'Authorization: Bearer ${AUTHORIZATION_TOKEN}' \ --header 'Content-Type: application/json-rpc' \ --data '{"jsonrpc":"2.0","method":"item.update","params":{"itemid":"10092","status":0},"id":5}' ``` The successful response will contain the ID of the updated item: ```json { "jsonrpc": "2.0", "result": { "itemids": [ "10092" ] }, "id": 5 } ``` ::: notetip The `item.update` method as well as other *update methods* can also accept arrays of objects and update multiple items with one API call. :::
zh-cn	#### 更新监控项 通过将其状态设置为 "0" 来启用监控项： ```bash curl --request POST \ --url 'https://example.com/zabbix/api_jsonrpc.php' \ --header 'Authorization: Bearer ${AUTHORIZATION_TOKEN}' \ --header 'Content-Type: application/json-rpc' \ --data '{"jsonrpc":"2.0","method":"item.update","params":{"itemid":"10092","status":0},"id":5}' ``` 成功的响应将包含更新后的监控项的 ID： ```json { "jsonrpc": "2.0", "result": { "itemids": [ "10092" ] }, "id": 5 } ``` ::: notetip `item.update` 方法以及其他 *更新方法* 也可以接受对象数组，并用一个 API 调用更新多个监控项。 :::

en	#### Updating multiple triggers Enable multiple triggers by setting their status to "0": ```bash curl --request POST \ --url 'https://example.com/zabbix/api_jsonrpc.php' \ --header 'Authorization: Bearer ${AUTHORIZATION_TOKEN}' \ --header 'Content-Type: application/json-rpc' \ --data '{"jsonrpc":"2.0","method":"trigger.update","params":[{"triggerid":"13938","status":0},{"triggerid":"13939","status":0}],"id":6}' ``` The successful response will contain the IDs of the updated triggers: ```json { "jsonrpc": "2.0", "result": { "triggerids": [ "13938", "13939" ] }, "id": 6 } ``` ::: notetip This is the preferred method of updating. Some API methods, such as the `host.massupdate` allow to write a simpler code. However, it is not recommended to use these methods as they will be removed in the future releases. :::
zh-cn	#### 更新多个触发器 通过将其状态设置为 "0" 来启用多个触发器： ```bash curl --request POST \ --url 'https://example.com/zabbix/api_jsonrpc.php' \ --header 'Authorization: Bearer ${AUTHORIZATION_TOKEN}' \ --header 'Content-Type: application/json-rpc' \ --data '{"jsonrpc":"2.0","method":"trigger.update","params":[{"triggerid":"13938","status":0},{"triggerid":"13939","status":0}],"id":6}' ``` 成功的响应将包含更新后的触发器的 ID： ```json { "jsonrpc": "2.0", "result": { "triggerids": [ "13938", "13939" ] }, "id": 6 } ``` ::: notetip 这是更新的首选方法。一些 API 方法，如 `host.massupdate`，允许编写更简单的代码。 然而，不建议使用这些方法，因为它们将在未来版本中被移除。 :::

en	#### Error handling Up to the present moment, everything you have tried has worked fine. But what would happen if you tried making an incorrect call to the API? Try to create another host by calling [host.create](/manual/api/reference/host/create) but omitting the mandatory `groups` parameter: ```bash curl --request POST \ --url 'https://example.com/zabbix/api_jsonrpc.php' \ --header 'Authorization: Bearer ${AUTHORIZATION_TOKEN}' \ --header 'Content-Type: application/json-rpc' \ --data '{"jsonrpc":"2.0","method":"host.create","params":{"host":"Linux server","interfaces":[{"type":1,"main":1,"useip":1,"ip":"192.168.3.1","dns":"","port":"10050"}]},"id":7}' ``` The response will then contain an error message: ```json { "jsonrpc": "2.0", "error": { "code": -32602, "message": "Invalid params.", "data": "No groups for host \"Linux server\"." }, "id": 7 } ``` If an error has occurred, instead of the `result` property, the response object will contain the `error` property with the following data: - `code` - an error code; - `message` - a short error summary; - `data` - a more detailed error message. Errors can occur in various cases, such as, using incorrect input values, a session timeout or trying to access non-existing objects. Your application should be able to gracefully handle these kinds of errors.
zh-cn	#### 错误处理 到目前为止，您尝试的所有操作都运行良好。但是，如果您尝试对 API 进行错误的调用会发生什么呢？尝试通过调用 [host.create](/manual/api/reference/host/create) 来创建另一个主机，但省略必填的 `groups` 参数： ```bash curl --request POST \ --url 'https://example.com/zabbix/api_jsonrpc.php' \ --header 'Authorization: Bearer ${AUTHORIZATION_TOKEN}' \ --header 'Content-Type: application/json-rpc' \ --data '{"jsonrpc":"2.0","method":"host.create","params":{"host":"Linux server","interfaces":[{"type":1,"main":1,"useip":1,"ip":"192.168.3.1","dns":"","port":"10050"}]},"id":7}' ``` 响应将包含一个错误信息： ```json { "jsonrpc": "2.0", "error": { "code": -32602, "message": "Invalid params.", "data": "No groups for host \"Linux server\"." }, "id": 7 } ``` 如果发生错误，响应对象将包含 `error` 属性而不是 `result` 属性，其中包含以下数据： - `code` - 错误代码； - `message` - 简短的错误摘要； - `data` - 更详细的错误信息。 在各种情况下都可能发生错误，例如，使用错误的输入值、会话超时或尝试访问不存在的对象。您的应用程序应该能够优雅地处理这些类型的错误。

en	### API versions To simplify API versioning, since Zabbix 2.0.4, the version of the API matches the version of Zabbix itself. You can use the [apiinfo.version](/manual/api/reference/apiinfo/version) method to find out the version of the API you are working with. This can be useful for adjusting your application to use version-specific features. Zabbix guarantees feature backward compatibility inside a major version. When making backward incompatible changes between major releases, Zabbix usually leaves the old features as deprecated in the next release, and only removes them in the release after that. Occasionally, Zabbix may remove features between major releases without providing any backward compatibility. It is important that you never rely on any deprecated features and migrate to newer alternatives as soon as possible. ::: notetip You can follow all the changes made to the API in the [API changelog](/manual/api/changes). :::
zh-cn	### API 版本 为了简化 API 版本管理，自 Zabbix 2.0.4 起，API 的版本与 Zabbix 本身的版本相匹配。您可以使用 [apiinfo.version](/manual/api/reference/apiinfo/version) 方法来查看您正在使用的 API 版本。这对于调整您的应用程序以使用特定版本的功能非常有用。 Zabbix 保证在同一主要版本内的向后兼容性。当在主要版本之间进行不向后兼容的更改时，Zabbix 通常会在下一个版本中将旧功能标记为已弃用，并在随后的版本中删除它们。偶尔，Zabbix 可能会在主要版本之间移除功能，而不提供任何向后兼容性。重要的是，您永远不要依赖任何已弃用的功能，并尽快迁移到较新的替代方案。 ::: notetip 您可以在 [API 更新日志](/manual/api/changes) 中查看对 API 所做的所有更改。 :::

en	### Further reading Now, you have enough knowledge to start working with the Zabbix API, however, do not stop here. For further reading you are advised to have a look at the [list of available APIs](/manual/api/reference).
zh-cn	### 进一步阅读 现在，您已经掌握了足够的知识来开始使用Zabbix API，但请不要就此止步。为了进一步学习，建议您查阅[可用 API 列表](/manual/api/reference)。