Skip to content

REST API

EMQX exposes an HTTP management API that follows the OpenAPI 3.0 specification.

This page is intended for developers and operators who integrate with or automate EMQX through its REST API.

EMQX provides multiple ways to explore and interact with the REST API. After EMQX is started, the following API specification endpoints are available:

EndpointFormatDescription
/api-spec.htmlHTMLDrill-down style API reference page for human reading.
/api-spec.mdMarkdownAPI reference in Markdown format, suited for AI agents and automation tools.
/api-spec.jsonJSONOpenAPI 3.0 specification in JSON format, suited for scripts and programmatic tooling.
/api-spec/:tag[/:name]JSONFocused OpenAPI 3.0 specification for an API tag, optionally narrowed by a matching request or response schema name.
/api-docs/swagger.jsonJSONFull OpenAPI 3.0 specification for external Swagger UI deployments and other compatible tools.

All of the above endpoints require swagger_support to be set to true (the default) in the Dashboard configuration. Set it to false to disable all API documentation endpoints. For more information, see Dashboard configuration.

Starting from EMQX 6.3.0, EMQX no longer bundles Swagger UI. For backward compatibility, requests to /api-docs or /api-docs/index.html return HTTP 308 and redirect to /api-spec.html. The redirect endpoints do not require authentication, but /api-spec.html requires authentication after the redirect. Except for /api-docs/index.html and /api-docs/swagger.json, other /api-docs/* subpaths that previously served Swagger UI assets return HTTP 404.

This section introduces how to work with the EMQX REST API.

TIP

Starting from EMQX 6.3.0, feature gates can disable optional features at startup. REST API paths provided by disabled features are not loaded as accessible API endpoints. When the dashboard feature is enabled, you can call GET /api/v5/features to view the resolved feature set.

Access API Specification Endpoints

Starting from EMQX 6.3.0, you must authenticate to retrieve API specification content from the endpoints listed above.

Programmatic Access

Authenticate programmatic requests with either Basic authentication using an API key and secret key or a bearer token. For instructions, see Authentication.

Access to the API specification is read-only and does not depend on the API key's role or scopes.

For /api-spec.md, /api-spec.json, /api-spec/:tag[/:name], and /api-docs/swagger.json, a request with missing or invalid credentials returns HTTP 401.

The response body uses the requested format but contains a minimal API specification instead of the requested API specification content. The minimal specification describes the supported authentication schemes and lists the following public authentication and status endpoints:

  • POST /api/v5/login/challenge and POST /api/v5/login/verify for SCRAM login.
  • POST /api/v5/login for legacy password login. This endpoint accepts password login only when dashboard.password_login is set to both.
  • GET /api/v5/status for checking whether the broker is running.

Browser Access

For browser access, open /api-spec.html. EMQX accepts a valid emqx_auth session cookie. An unauthenticated request returns HTTP 401 and displays the EMQX sign-in page instead of the full API Spec Explorer or the browser's native Basic authentication dialog.

Starting from EMQX 6.3.1, the sign-in page uses SCRAM-SHA-256 by default. Open the page through HTTPS or another secure browser context. TLS can terminate at a reverse proxy or load balancer; the EMQX Dashboard listener itself does not have to use HTTPS.

After you sign in with your Dashboard username and password, EMQX creates the emqx_auth session cookie and loads the full explorer. Signing out clears the session cookie.

Basic Path

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

HTTP Headers

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

HTTP Response Status Code

EMQX follows the HTTP Response Status Code standard. 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. Authentication credentials are missing, invalid, or expired.
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

Authentication

EMQX's REST API supports two main methods for authentication: basic authentication using API keys and bearer token authentication.

Basic Authentication Using API Keys

In this method, you use API keys and secret keys as the username and password to authenticate your API requests. EMQX's REST API follows HTTP Basic Authentication, where these credentials are required. Before using the EMQX REST API, you must create an API key. See API Key Management for details.

Note

Starting from EMQX 5.0.0, Dashboard usernames and passwords cannot be used directly as Basic authentication credentials for REST API requests. To authenticate with local Dashboard user credentials, use a Dashboard login flow to obtain a short-lived bearer token. For long-running programmatic access, use API keys.

Dashboard login, SSO callbacks, and API key self-management endpoints (for example, /api_key) do not accept API-key authentication, regardless of the key's scopes configuration. This is a built-in Dashboard security boundary, unrelated to the scope model.

Authenticate with API Keys

Once you have your API key and secret key, use the API key as the username and the secret key as the password for Basic Authentication.

Examples in different languages:

Bearer Token Authentication

Choose the authentication method according to how the client accesses EMQX:

  • For long-running services and unattended automation, use API keys because Dashboard login tokens expire.
  • Starting in EMQX 6.3.1, use SCRAM-SHA-256 challenge-response authentication to obtain a short-lived bearer token with local Dashboard user credentials.

Obtain a Bearer Token with SCRAM-SHA-256

To obtain a bearer token through SCRAM without sending the password in an HTTP request body:

  1. Generate a random client nonce containing 20 to 128 unpadded Base64URL characters.

  2. Send the username and client nonce to POST /api/v5/login/challenge.

  3. Append the returned server nonce to the client nonce to form the combined nonce.

  4. Construct the RFC 7677 SCRAM-SHA-256 messages using the username and client_nonce retained from the challenge request, and the server_nonce, salt, and iterations returned in the challenge response:

    text
    client-first-message-bare = n=<escaped_username>,r=<client_nonce>
    server-first-message = r=<combined_nonce>,s=<salt>,i=<iterations>
    client-final-message-without-proof = c=biws,r=<combined_nonce>
    auth-message = <client-first-message-bare>,<server-first-message>,<client-final-message-without-proof>

    Escape the username according to RFC 5802 by first replacing = with =3D and then replacing , with =2C. Use the Base64-encoded salt value returned by the challenge endpoint in server-first-message.

  5. Calculate the client proof and expected server signature as follows. HMAC-SHA-256(key, message) indicates the key and message arguments in that order. UTF8(value) encodes a string as UTF-8 bytes, Base64Decode(value) decodes a Base64 string, and XOR applies a byte-wise exclusive OR.

    text
    salted-password = PBKDF2-HMAC-SHA-256(UTF8(password), Base64Decode(salt), iterations, 32 bytes)
    client-key = HMAC-SHA-256(salted-password, "Client Key")
    stored-key = SHA-256(client-key)
    client-signature = HMAC-SHA-256(stored-key, UTF8(auth-message))
    client-proof = client-key XOR client-signature
    server-key = HMAC-SHA-256(salted-password, "Server Key")
    expected-server-signature = HMAC-SHA-256(server-key, UTF8(auth-message))

    Base64-encode client-proof and send it in the client_proof field of the POST /api/v5/login/verify request together with the challenge ID and combined nonce. Include mfa_token when multi-factor authentication is enabled for the user.

  6. Base64-decode the server_signature in the response and compare it with expected-server-signature before using the bearer token in the token field.

Each challenge is time-limited. A well-formed request to POST /api/v5/login/verify consumes the challenge whether authentication succeeds or fails, including when the request returns BAD_MFA_TOKEN. Requests rejected during preliminary validation, such as an invalid Base64 encoding or decoded length for client_proof, or an invalid combined_nonce format, do not consume the challenge and can be retried. After a consumed challenge fails, request a new challenge and recalculate the client proof.

For the request and response schemas, open the dashboard section of the API specification.

Browser-based SCRAM login requires HTTPS or another secure browser context.

Obtain a Bearer Token with Password Login

The compatibility endpoint POST /api/v5/login accepts a username and password only when dashboard.password_login is set to both, which is the default. If dashboard.password_login is set to scram_only, the endpoint returns HTTP 403 with the error code PASSWORD_LOGIN_DISABLED. Use the SCRAM flow described above or an API key instead.

When password login is enabled, use the following endpoint for local access:

bash
POST http://localhost:18083/api/v5/login

Headers:

  • Content-Type: application/json

Request Body:

json
{
  "username": "admin",
  "password": "yourpassword"
}
  • Replace "admin" and "yourpassword" with your EMQX Dashboard credentials.

This example uses HTTP on localhost. For remote access, configure an HTTPS listener and send the request over HTTPS.

The response will include the bearer token, which you can use to authenticate API requests.

Use Bearer Token for Authentication

Once you have the bearer token, include it in the Authorization header of your API requests, like this:

bash
--header "Authorization: Bearer <your-token>"

API Key Management

This section describes how to create and manage API keys and configure their roles, namespaces, and scopes.

Create API Keys

Dashboard

You can manually create API keys on the Dashboard by navigating to System -> API Keys:

  1. Click the + Create button in the top right corner to open the Create dialog.

  2. Configure the API key details:

    • Name (required): Enter a name for the API key.
    • Expire At: Leave empty for the key to never expire.
    • Is Enable: Defaults to enabled.
    • Role: Select a role (optional). See Roles and Permissions.
    • Namespace: The switch is off by default. For a global administrator, leaving it off creates a global API key. Turn it on and select a namespace to create the key in that namespace. A namespaced administrator can create keys only in their own namespace.
    • Permission Mode: For an Administrator or Viewer key, select how to assign scopes. This field is not displayed for Publisher keys, which use the role-default publish scope. For scope behavior and restrictions, see API Scopes.
      • Role Default Scopes: Use the defaults for the selected role. Changes to the role defaults take effect automatically.
      • System-level Permissions: Grant only the system scope.
      • Custom Restricted Permissions: Select one or more scopes to limit which API areas the key can access. If you leave Scopes empty, the key cannot access scope-protected APIs.
    • Scopes: Appears when you select Custom Restricted Permissions. Select the scopes to grant.
    • Note: Optionally enter a description for the key.
  3. Click Confirm. The API key and secret key are displayed in the Created Successfully dialog.

    Important Notice

    Save the API key and secret key immediately. The secret key will not be shown again.

  4. Click Close to dismiss the dialog.

Permission Mode is available only in the Dashboard. When using the REST API, configure the scopes field directly. For details, see Default Behavior of scopes.

You can view key details by clicking its name. Use the Edit button to change its expiration, status, role, permission mode, scopes, or note. Use the Delete button to remove the key.

REST API

Use a Dashboard user's bearer token to create or update an API key through the REST API. The API key management endpoints do not accept API key authentication.

Starting from EMQX 6.0.4, the request body for POST /api/v5/api_key and PUT /api/v5/api_key/:name accepts a top-level namespace field. For example, the following request creates an administrator API key in the team-a namespace:

bash
curl -X POST "http://localhost:18083/api/v5/api_key" \
  -H "Authorization: Bearer <your-token>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "team-a-key",
    "role": "administrator",
    "namespace": "team-a",
    "scopes": "unset"
  }'

Setting scopes to "unset" explicitly applies the role-default scopes. Omitting scopes from a create request has the same effect.

You can specify the namespace in either of these ways:

  • Provide a bare role, such as administrator, together with the namespace field.
  • Encode the namespace in the role as ns:<namespace>::<role>, such as ns:team-a::administrator.

Both forms remain supported. If a request contains both forms, the namespaces must match. EMQX returns HTTP 400 if they differ or if namespace is empty. After an API key is created, its namespace cannot be changed through the REST API.

Starting from EMQX 6.3.0, neither form can use a namespace listed in multi_tenancy.deny_namespaces. For configuration details, see Denied Namespace Names.

To create a global API key, omit namespace and use a role without a namespace prefix. Setting namespace to the string "global" does not select the global scope.

Bootstrap File

You can also create API keys using the bootstrap file method. Add the following configuration file to specify the file location:

bash
api_key = {
  bootstrap_file = "etc/default_api_key.conf"
}

In the specified file, add multiple API keys in the format {API Key}:{Secret Key}:{?Role}:{?Scopes}, separated by new lines:

  • API Key: Any string as the key identifier.
  • Secret Key: Use a random string as the secret key.
  • Role (optional): Specify the key's role. For a namespaced key, use ns:<namespace>::<role>, for example, ns:team-a::administrator.
  • Scopes (optional): Specify the API Scopes the key is allowed to access as a comma-separated list. When omitted, the key receives the defaults for its role. For validation behavior, see Validate Bootstrap Scopes.

For example:

bash
my-app:AAA4A275-BEEC-4AF8-B70B-DAAC0341F8EB
ec3907f865805db0:Ee3taYltUKtoBVD9C3XjQl9C6NXheip8Z9B69BpUv5JxVHL:viewer
foo:3CA92E5F-30AB-41F5-B3E6-8D7E213BE97E:publisher
integration-svc:6f1a9f2d09c84e6b:viewer:monitoring,cluster_operations
rules-mgr:2b8e4a1c9d7e4f3b:administrator:data_integration,access_control
team-a-ops:8d4f2a7c1e6b9035:ns:team-a::administrator:connections,monitoring
Validate Bootstrap Scopes

When a bootstrap entry violates one of the following scope rules, EMQX removes the affected scopes, logs a warning, and continues to create or update the key:

  • Login-only scopes: user_management, mfa_management, sso_management, and api_key_management are not valid for API keys. EMQX removes these scopes and creates or updates the key with the remaining scopes.
  • Administrator-equivalent scopes: Among the scopes that can be assigned to API keys, system is the only one that grants administrator-equivalent permissions. Starting from EMQX 6.0.4, if an entry combines an administrator-equivalent scope with scopes that do not grant administrator-equivalent permissions, EMQX removes all administrator-equivalent scopes and keeps the remaining scopes.
  • Namespaced scopes: Starting from EMQX 6.3.1, if a namespaced entry explicitly lists scopes that the namespaced role cannot hold, EMQX removes the disallowed scopes and keeps the remaining scopes. If no scopes remain, the key cannot access scope-protected business APIs. For the allowed scopes, see Restrictions for Namespaced Callers.
Reload Bootstrap API Keys

API keys created from the bootstrap file are valid indefinitely. EMQX processes the file each time it starts. If an API key already exists, EMQX updates its role, namespace, and scopes.

Starting from EMQX 6.3.1, if the Secret Key in the file is unchanged, EMQX preserves the stored secret hash. If the Secret Key has changed, EMQX generates a new hash, and the previous Secret Key stops working.

Important Notice

During a rolling upgrade from EMQX 6.2 to 6.3.1, do not change a bootstrap API key's Secret Key until every node runs EMQX 6.3. A changed Secret Key is stored using the 6.3 hash format, which nodes still running 6.2 cannot verify.

Manage API Keys as a Namespaced Administrator

Starting from EMQX 6.0.4, a namespaced Dashboard administrator can manage API keys within their own namespace. The administrator must authenticate with a bearer token.

OperationNamespaced Administrator Behavior
Create an API keyCan create a key only in the administrator's namespace. Omitting the namespace, specifying the global namespace, or specifying another namespace returns HTTP 403.
List API keysSees only keys in the administrator's namespace. Global keys and keys in other namespaces are filtered from the response.
Read, update, or delete an API keyCan operate only on keys in the administrator's namespace. A key in another namespace returns HTTP 404 so that its existence is not disclosed.
Change an API key's namespaceCannot move a key to another namespace. The update returns HTTP 400.

A global Dashboard administrator can continue to manage API keys across all namespaces.

API Key Permissions

Roles and Permissions

The REST API implements role-based access control. When creating an API key, you can assign one of the following three predefined roles:

  • Administrator: This role can access all resources and is the default value if no role is specified. The corresponding role identifier is administrator.
  • Viewer: This role can only view resources and data, corresponding to all GET requests in the REST API. The corresponding role identifier is viewer.
  • Publisher: Designed specifically for MQTT message publishing, this role is limited to accessing APIs related to message publishing. The corresponding role identifier is publisher.

Note

publisher keys only accept the publish scope. When assigning scopes, any scope other than publish returns HTTP 400. If you change a key's role to publisher, include "scopes": ["publish"] or an empty list in the same request; otherwise the request is rejected if the key's existing scopes contain anything other than publish.

API Scopes

Scopes are a per-key permission dimension that declares which business areas of the REST API a key is allowed to reach. Scopes and Roles and Permissions are independent of each other and enforced together, forming two separate layers of access control:

DimensionPurposeGranularity
RoleLimits HTTP verbs (read-only vs. writes, publish-only, etc.)Request action
ScopeLimits the API domain (clients, rules, monitoring, ...)Resource area

Every request is checked against both dimensions: the role check and the scope check. A request is accepted only when both checks pass.

In microservice and integration scenarios, external systems typically need access to only a subset of EMQX's management surface: a monitoring platform only needs the monitoring scope, a rules-publishing service only needs data_integration, and a cluster operator tool only needs cluster_operations. Scopes let you assign keys using the principle of least privilege, minimizing the blast radius if a key is ever leaked.

TIP

Scope names are stable identifiers that do not change across EMQX upgrades. Even if a route's OpenAPI tag is renamed, a key configured with the same scope keeps working.

Built-in API Key Scopes

EMQX provides 10 scopes for API keys:

ScopeNameTypical API areas
connectionsConnection management/clients, /subscriptions, /topics, /banned, /retainer, /file_transfer, /mqtt/delayed, /mqtt/topic_rewrite, ...
publishMessage publishing/publish, /publish/bulk
data_integrationData integration/rules, /connectors, /actions, /schema_registry, /schema_validations, /message_transformations, /exhooks, /ai/*
access_controlAccess control/authentication, /authorization/*
gatewaysProtocol gateways/gateways, /coap/*, /lwm2m/*, /gcp_devices, ...
monitoringMonitoring data/metrics, /stats, /monitor*, /alarms, /trace, /slow_subscriptions, /telemetry, /prometheus/{auth,stats,data_integration,...}, ...
cluster_operationsCluster operations/cluster*, /nodes, /load_rebalance, /node_eviction, /mt/*, ...
systemSystem configuration/configs*, /listeners*, /plugins*, /ds/*, /data/*, /status, /relup, /opentelemetry*, /prometheus, ...
auditAudit log/audit
licenseLicense/license*

Do Not Mix Administrator-Equivalent and Restricted Scopes

EMQX classifies system, user_management, api_key_management, and sso_management as administrator-equivalent scopes, referred to as privilege scopes in validation messages. Combining these scopes with restricted scopes would not reduce the account's effective permissions. Of the four scopes, only system can be assigned to API keys; the other three are described under Login-Only Scopes.

Therefore, starting from EMQX 6.0.4, an explicit scope list used to create or update an API key must contain either system alone or scopes that do not include system. A mixed list returns HTTP 400, and no changes are applied.

Existing mixed scope lists continue to work, with system remaining effective. The next explicit scope update must use either system alone or a list that does not include system. When such a key is edited in the Dashboard, the user is prompted to select a permission mode before saving.

Login-Only Scopes

In addition to these API-key scopes, Dashboard login users have 4 login-only scopes that apply exclusively to browser sessions and cannot be assigned to API keys. For details on how these scopes are assigned and enforced for login users, see Login User Scopes.

ScopeRequired rolePurpose
user_managementAdministratorManage Dashboard users.
sso_managementAdministratorManage SSO backends and SSO user records.
api_key_managementAdministratorManage API keys.
mfa_managementAnyManage MFA for own account; administrators can manage other users' MFA.

Default Behavior of scopes

Starting from EMQX 6.0.4, the scopes field on an API key follows these rules:

Value of scopesMeaning
Absent in a create requestUse the defaults for the selected role.
Absent in an update requestPreserve the key's current scope setting.
Role-default sentinel "unset"Remove the explicit scope setting and use the defaults for the selected role. Changes to the role defaults take effect automatically.
Empty list []Every business endpoint is denied. Useful as a soft disable without removing the key.
Explicit list (e.g. ["monitoring", "cluster_operations"])Only requests under those scopes are allowed.

An explicit list that contains the same set of scopes as the role defaults has the same effect as "unset". The key continues to follow changes to the role defaults. The comparison is order-independent.

When a bootstrap file entry omits the scopes segment, EMQX applies the defaults for the specified role when processing the file.

Scopes determine which API areas a key can access. They do not override the key's role or namespace restrictions. A request is allowed only when its role, scope, and namespace checks all pass.

List Available Scopes

EMQX exposes two endpoints to query the available scope catalogues:

  • GET /api/v5/api_key_scopes: returns the scopes that can be assigned to API keys (the 10 business-domain scopes listed above). Authenticate with an API key.
  • GET /api/v5/user_scopes: returns all scopes available to Dashboard login users, including the 4 login-only scopes. Authenticate with a bearer token.

Use these endpoints to populate a scope-picker UI or validate automation scripts:

bash
# API key scopes
curl -u "$API_KEY:$API_SECRET" http://localhost:18083/api/v5/api_key_scopes

# Login user scopes (requires bearer token)
curl -H "Authorization: Bearer $TOKEN" http://localhost:18083/api/v5/user_scopes

Assign Scopes

Scopes can be set from any of the following entry points:

  • Dashboard: When creating or editing a key under System -> API Keys, select a Permission Mode. Select individual scopes only for Custom Restricted Permissions.
  • REST API: Include "scopes": ["monitoring", "cluster_operations"] in the create/update request body.
  • Bootstrap file: Provide a comma-separated scope list as the 4th segment of each line, e.g. my-app:my-secret:administrator:monitoring,cluster_operations.

Restrictions for Namespaced Callers

Namespaced callers (users or API keys whose role is restricted to a specific namespace) are subject to additional endpoint-level restrictions beyond scope checks. Scope grants do not override these restrictions.

Scope Restrictions for Namespaced API Keys

Starting from EMQX 6.3.1, when creating a namespaced API key or changing an existing key's explicit scope list, only the connections, monitoring, data_integration, access_control, system, cluster_operations, and license scopes are allowed. If such a create or update request specifies publish, gateways, audit, or any other scope unavailable to a namespaced role, EMQX returns HTTP 400 and does not apply the change. The restriction against combining system with restricted scopes also applies.

Existing Keys with Disallowed Scopes

An existing key whose stored scope list contains disallowed scopes continues to work. For backward compatibility with read-modify-write clients, EMQX accepts the stored list when an update resubmits it unchanged and keeps the same role and namespace. Any actual role or scope change is revalidated and must comply with the allowlist. If an existing namespaced API key contains disallowed scopes, update or rotate the key and assign only scopes available to its namespaced role. When EMQX reprocesses the bootstrap file, it drops disallowed scopes, logs a warning, and keeps the rest; see Validate Bootstrap Scopes.

Message Publishing Restrictions

A legacy namespaced API key that still contains the publish scope cannot call message publishing APIs, including POST /api/v5/publish. Assigning a scope does not override namespace-level restrictions.

Message Content Restrictions

Even when a namespaced caller has the connections or monitoring scope, the caller cannot access cluster-wide endpoints that read or manipulate raw MQTT message content, including retained and delayed message stores. The following message-related endpoints return 403 Forbidden:

  • GET /clients/:clientid/mqueue_messages
  • GET /clients/:clientid/inflight_messages
  • GET /mqtt/retainer/messages
  • GET /mqtt/retainer/message/:topic
  • DELETE /mqtt/retainer/message/:topic
  • DELETE /mqtt/retainer/messages
  • GET /mqtt/delayed/messages
  • GET /mqtt/delayed/messages/:node/:msgid
  • DELETE /mqtt/delayed/messages/:node/:msgid
  • DELETE /mqtt/delayed/messages/:topic

Trace Restrictions

For trace operations, GET /trace lists only traces within the caller's namespace. The following per-trace operations return 404 Not Found when the trace belongs to a different namespace:

  • PUT /trace/:name/stop
  • GET /trace/:name/download
  • GET /trace/:name/log
  • GET /trace/:name/log_detail
  • DELETE /trace/:name

This behavior prevents the disclosure of traces in other namespaces. The bulk-delete operation (DELETE /trace) returns 403 Forbidden for namespaced callers; only global administrators can clear all traces.

Pagination

For some APIs with large amounts of data, pagination functionality is provided. There are 2 types of pagination methods based on the data characteristics.

Page Number Pagination

In most APIs that support pagination, you can control the pagination by using the page (page number) and limit (page size) parameters. The maximum page size is 10000. If the limit parameter is not specified, the default is 100.

For example:

bash
GET /clients?page=1&limit=100

In the response result, the meta field will contain pagination information. EMQX cannot predict the total number of data entries for requests using search conditions. Therefore, the meta.hasnext field indicates whether there is another page of data:

json
{
  "data":[],
  "meta":{
    "count":0,
    "limit":20,
    "page":1,
    "hasnext":false
  }
}

Cursor Pagination

In a few APIs where data changes rapidly, and page number pagination is inefficient, cursor pagination is used.

You can specify the starting position of the data using the position or cursor (starting position) parameter, and the limit (page size) parameter specifies the number of entries loaded from the starting position. The maximum page size is 10000. If the limit parameter is not specified, it defaults to 100.

For example:

bash
GET /clients/{clientid}/mqueue_messages?position=1716187698257189921_0&limit=100

The meta field in the response will contain pagination information, with meta.position or meta.cursor indicating the starting position of the next page:

json
{
    "meta": {
        "start": "1716187698009179275_0",
        "position": "1716187698491337643_0"
    },
    "data": [
        {
            "inserted_at": "1716187698260190832",
            "publish_at": 1716187698260,
            "from_clientid": "mqttx_70e2eecf_10",
            "from_username": "undefined",
            "msgid": "000618DD161F682DF4450000F4160011",
            "mqueue_priority": 0,
            "qos": 0,
            "topic": "t/1",
            "payload": "SGVsbG8gRnJvbSBNUVRUWCBDTEk="
        }
    ]
}

This pagination method efficiently handles scenarios where data changes rapidly, ensuring continuity and efficiency in data retrieval.

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:

bash
# GET /clients/foo

{
  "code": "RESOURCE_NOT_FOUND",
  "reason": "Client id not found"
}
Error CodesDescription
WRONG_USERNAME_OR_PWDWrong username or password
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