REST API

EMQX exposes an HTTP management API designed following OpenAPI (Swagger) 3.0 specification.

After EMQX is started, you can visit http://localhost:18083/api-docs/index.htmlREST API - 图1 (opens new window) to view the API document, and also execute the management APIs from this UI.

The section will introduce how to work with EMQX REST API.

Basic Path

EMQX has version control on the REST API, all API paths from EMQX 5.0.0 start with /api/v5.

Authentication

EMQX’s REST API uses HTTP Basic AuthenticationREST API - 图2 (opens new window).

To create an API key, you can click System -> API Key page on the left navigation menu of the Dashboard, Please refer to Dashboard - API Keys.

You can use the generated API Key and Secret Key as the username and password for Basic authentication:

  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 Headers

Unless otherwise specified, most API requests require the Accept header to be set to application/json, and then the response will be returned in JSON format.

HTTP Response Status Code

EMQX follows the HTTP Response Status CodeREST API - 图3 (opens new window) standard, and the possible status codes are as follows:

CodesDescription
200Request successfully, and the returned JSON data will provide more details
201Created successfully, and the new object will be returned in the Body
204Request successfully. Usually used for delete and update operations, and the returned Body will be empty
400Bad Request. Usually request body or parameter error
401Unauthorized. API key expires or does not exist.
403Forbidden. Check if the object is in use or has dependency constraints.
404Not Found. You can refer to the message field in the Body to check the reason
409Conflict. The object already exists or the number limit is exceeded
500Internal Server Error. Check the reason in the Body and logs

Error Codes

Besides the HTTP response status codes, EMQX also defines a list of error codes to identify specific errors.

When an error happens, the error code is returned in JSON format by the Body:

  1. # GET /clients/foo
  2. {
  3. "code": "RESOURCE_NOT_FOUND",
  4. "reason": "Client id not found"
  5. }
Error CodesDescription
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