REST API

EMQX 提供了管理监控 REST API,这些 API 遵循 OpenAPI (Swagger) 3.0 规范。

EMQX 服务启动后,您可以访问 http://localhost:18083/api-docs/index.htmlREST API - 图1 (opens new window) 来查看 API 的文档。还可以直接在 Swagger UI 上尝试执行一些 API。

本章节将指导您快速开始使用 EMQX REST API。

基本路径

EMQX 在 REST API 上做了版本控制,EMQX 5.0.0 以后的所有 API 调用均以 /api/v5 开头。

认证

EMQX 的 REST API 使用 HTTP Basic 认证REST API - 图2 (opens new window) 携带认证凭据,您可以在 Dashboard 系统设置 -> API 密钥 界面中创建用于认证的 API 密钥,详细操作请参考 Dashboard - API 密钥

使用生成的 API Key 以及 Secret Key 分别作为 Basic 认证的用户名与密码,请求示例如下:

  1. curl -X GET http://localhost:18083/api/v5/nodes \
  2. -u 4f33d24d7b8e448d:gwtbmFJZrnzUu8mPK1BxUkBA66PygETiDEegkf1q8dD \
  3. -H "Content-Type: application/json"
  1. import okhttp3.*;
  2. import java.io.IOException;
  3. public class EMQXNodesAPIExample {
  4. public static void main(String[] args) {
  5. try {
  6. String username = "4f33d24d7b8e448d";
  7. String password = "gwtbmFJZrnzUu8mPK1BxUkBA66PygETiDEegkf1q8dD";
  8. OkHttpClient client = new OkHttpClient();
  9. Request request = new Request.Builder()
  10. .url("http://localhost:18083/api/v5/nodes")
  11. .header("Content-Type", "application/json")
  12. .header("Authorization", Credentials.basic(username, password))
  13. .build();
  14. Response response = client.newCall(request).execute();
  15. System.out.println(response.body().string());
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. }
  1. import urllib.request
  2. import json
  3. import base64
  4. username = '4f33d24d7b8e448d'
  5. password = 'gwtbmFJZrnzUu8mPK1BxUkBA66PygETiDEegkf1q8dD'
  6. url = 'http://localhost:18083/api/v5/nodes'
  7. req = urllib.request.Request(url)
  8. req.add_header('Content-Type', 'application/json')
  9. auth_header = "Basic " + base64.b64encode((username + ":" + password).encode()).decode()
  10. req.add_header('Authorization', auth_header)
  11. with urllib.request.urlopen(req) as response:
  12. data = json.loads(response.read().decode())
  13. print(data)
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "bytes"
  6. "encoding/json"
  7. )
  8. func main() {
  9. username := "4f33d24d7b8e448d"
  10. password := "gwtbmFJZrnzUu8mPK1BxUkBA66PygETiDEegkf1q8dD"
  11. url := "http://localhost:18083/api/v5/nodes"
  12. req, err := http.NewRequest("GET", url, nil)
  13. if err != nil {
  14. panic(err)
  15. }
  16. req.SetBasicAuth(username, password)
  17. req.Header.Set("Content-Type", "application/json")
  18. client := &http.Client{}
  19. resp, err := client.Do(req)
  20. if err != nil {
  21. panic(err)
  22. }
  23. defer resp.Body.Close()
  24. buf := new(bytes.Buffer)
  25. _, err = buf.ReadFrom(resp.Body)
  26. if err != nil {
  27. panic(err)
  28. }
  29. var data interface{}
  30. json.Unmarshal(buf.Bytes(), &data)
  31. fmt.Println(data)
  32. }
  1. const axios = require('axios')
  2. const username = '4f33d24d7b8e448d'
  3. const password = 'gwtbmFJZrnzUu8mPK1BxUkBA66PygETiDEegkf1q8dD'
  4. axios
  5. .get('http://localhost:18083/api/v5/nodes', {
  6. auth: {
  7. username: username,
  8. password: password,
  9. },
  10. headers: {
  11. 'Content-Type': 'application/json',
  12. },
  13. })
  14. .then((response) => {
  15. console.log(response.data)
  16. })
  17. .catch((error) => {
  18. console.log(error)
  19. })

HTTP 请求头

除非有特殊说明,绝大多数 API 要求请求头中 Accept 值设置为 application/json,响应内容将以 JSON 格式返回。

HTTP 响应状态码

EMQX 遵循HTTP 响应状态码REST API - 图3 (opens new window)标准,可能的状态码如下:

状态码描述
200请求成功,返回的 JSON 数据将提供更多信息
201创建成功,新建的对象将在 Body 中返回
204请求成功,常用于删除与更新操作,Body 不会返回内容
400请求无效,例如请求体或参数错误
401未通过服务端认证,API 密钥过期或不存在时可能会发生
403无权操作,检查操作对象是否正在使用或有依赖约束
404找不到请求路径或请求的对象不存在,可参照 Body 中的 message 字段判断具体原因
409请求的资源已存在或数量超过限制
500服务端处理请求时发生内部错误,可通过 Body 返回内容与日志判断具体原因

错误码

HTTP 响应状态码能够直观的判断可能存在的问题,在此基础上 EMQX 定义了一系列的错误码来标识具体的错误原因。当发生错误时,错误码将通过 Body 以 JSON 格式返回,您可以根据错误码 code 了解错误分类,根据原因 reason 了解具体的错误信息:

  1. # GET /clients/foo
  2. {
  3. "code": "RESOURCE_NOT_FOUND",
  4. "reason": "Client id not found"
  5. }
错误码描述
WRONG_USERNAME_OR_PWDWrong username or password REST API - 图4
WRONG_USERNAME_OR_PWD_OR_API_KEY_OR_API_SECRETWrong username & password or key & secret
BAD_REQUESTRequest parameters not legal
NOT_MATCHConditions not matched
ALREADY_EXISTSResources already exist
BAD_CONFIG_SCHEMAConfiguration data not legal
BAD_LISTENER_IDBad listener ID
BAD_NODE_NAMEBad Node Name
BAD_RPCRPC Failed. Check the cluster status and the requested node status
BAD_TOPICTopic syntax error, topic needs to comply with the MQTT protocol standard
EXCEED_LIMITResources to be created exceed the maximum limit or minimum limit
INVALID_PARAMETERRequest parameters not legal and exceed the boundary value
CONFLICTConflicting request resources
NO_DEFAULT_VALUERequest parameters do not use default values
DEPENDENCY_EXISTSResource depends on other resources
MESSAGE_ID_SCHEMA_ERRORMessage ID parsing error
INVALID_IDBad ID schema
MESSAGE_ID_NOT_FOUNDMessage ID does not exist
NOT_FOUNDResource not found or does not exist
CLIENTID_NOT_FOUNDClient ID not found or does not exist
CLIENT_NOT_FOUNDClient not found or does not exist(usually not an MQTT client)
RESOURCE_NOT_FOUNDResource not found
TOPIC_NOT_FOUNDTopic not found
USER_NOT_FOUNDUser not found
INTERNAL_ERRORServer inter error
SERVICE_UNAVAILABLEService unavailable
SOURCE_ERRORSource error
UPDATE_FAILEDUpdate fails
REST_FAILEDReset source or configuration fails
CLIENT_NOT_RESPONSEClient not responding