Contact Us 1-800-596-4880

Anypoint MQ REST APIs

The Anypoint MQ APIs enable you to use REST to send and receive messages, administer queues and message exchanges, and analyze results.

Anypoint MQ provides these APIs:

Anypoint MQ APIs are available in the Developer portal.

Workflow for an API

This example illustrates the workflow for accessing the Anypoint MQ Broker API:

Workflow of the Anypoint MQ Broker API
  1. An app sends a request to Anypoint MQ and sets how long to hold the lock on the message.

  2. Anypoint MQ sends the message and the lock ID.

  3. The app acknowledges the message and requests Anypoint MQ to delete the message, or the app negatively acknowledges the message and requests Anypoint MQ to make the message available to other apps. The app sends the message ID and lock ID to Anypoint MQ. For more information, see ACK and NACK Operations.

  4. If no action is taken and the duration of a lock’s time to live expires, the message is negatively acknowledged and returns to the queue to be available for other apps.

Before You Begin

  • Create an app that uses Anypoint MQ and deploy it to CloudHub.

  • Get a bearer token for an Anypoint Platform user using the Access Management API.

    You need the bearer token to access all Anypoint MQ APIs.

  • Get the ORG_ID and ENV_ID.

    You need the organization ID and environment ID for operations with all Anypoint MQ APIs.

  • Get the REGION_ID.

    You need the region ID for operations with the Anypoint MQ Admin API.

  • Get the QUEUE_ID.

    You need the queue ID for operations with the Anypoint MQ Admin API.

Get the Bearer Token to Use With Anypoint MQ APIs

To access the Anypoint MQ APIs, you must first get the bearer token from the Anypoint Platform user using the Access Management API.

The default time to live (TTL) for the bearer token is 60 minutes.
If MFA (multi-factor authentication) is enabled

Use a connected app to get the bearer token:

  1. Create a connected app.

  2. Assign the connected app the Organization Administrator scope to access the organization and environment queries.

  3. From the Connected Apps page, click Copy Id and Copy Secret for the app you just created.

  4. Run this command and replace CLIENT_ID and CLIENT_SECRET with the values you copied from the connected app and AUTH_SERVER_HOST with the authorization server:

    curl --location 'https://<AUTH_SERVER_HOST>/accounts/api/v2/oauth2/token' \
    --header 'Content-Type: application/json' \
    --data '{
        "client_id": "<CLIENT_ID>",
        "client_secret": "<CLIENT_SECRET>",
        "grant_type": "client_credentials"
    }'

    The output includes the bearer token:

    {
        "access_token": "<BEARER_TOKEN>"
        "expires_in": 3600,
        "token_type": "bearer"
    }
  5. Use this bearer token to access any Anypoint MQ API that requires a bearer token.

If MFA isn’t enabled

Authenticate with the credentials of a user with the Organization Administrator permission:

  1. Run this command, replacing AUTH_SERVER_HOST with the authorization server, for example https://anypoint.mulesoft.com/

    curl -H \
      "Content-Type: application/json" \
      -X POST -d '{"username":"<USERNAME>","password":"<PASSWORD>"}' \
      "https://<AUTH_SERVER_HOST>/accounts/login"

    Make sure the user has the Organization Administrator permission to access the organization and environment queries.

    The output includes the token:

    {
      "access_token": "<BEARER_TOKEN>",
      "token_type": "bearer",
      "redirectUrl": "/home/"
    }
  2. Use this bearer token to access any Anypoint MQ API that requires a bearer token.

Get the Broker Bearer Token to Use With Anypoint MQ Broker API

For the Anypoint MQ Broker API, you can also get the bearer token from a client app.

MuleSoft recommends that you use connected apps rather than client apps to generate credentials. For information, see Configuring Connected Apps.

You can use the broker bearer token only with the Broker API. Don’t use this token with the Stats and Admin APIs. Instead, follow the steps in Get the Bearer Token to Use With Anypoint MQ APIs to get the bearer token.

All calls to get a token for a particular CLIENT_ID return the same token. Multiple apps using the same CLIENT_ID use the same token. The token is valid for 60 minutes. Accessing the token before its expiry extends the token validity by another 60 minutes.

To get the CLIENT_ID and CLIENT_SECRET from a client app
  1. Create a client app.

  2. From the Client Apps page, select the app you just created.

  3. Click Copy to copy the client app ID and client secret values to your clipboard.

To get the token required to authenticate with the Anypoint Platform API
  1. Run this command and replace CLIENT_ID and CLIENT_SECRET with the values you copied from the client app and AUTH_SERVER_HOST with the authorization server:

    curl -X POST "https://AUTH_SERVER_HOST/accounts/oauth2/token" \
    -H "Content-Type: application/json" \
    -d '{
        "client_id": "<CLIENT_ID>",
        "client_secret": "<CLIENT_SECRET>",
        "grant_type": "client_credentials"
    }'

    The command returns output similar to:

    {
      "access_token":"<BEARER_TOKEN>",
      "simple_client":{"envId":"<ENV_ID>","orgId":"<ORG_ID>"},
      "token_type":"bearer"
    }

Get the Organization ID and Environment ID

To get the ORG_ID, run this command, replacing AUTH_SERVER_HOST with the authorization server:

curl -X GET https://<AUTH_SERVER_HOST>/accounts/api/me \
  -H "Authorization: Bearer <BEARER_TOKEN>"

The response includes output similar to:

"organization": {
    "name": "MyCompany",
    "id": "ORG_ID",
  },

To get the ENV_ID, run this command, replacing AUTH_SERVER_HOST with the authorization server:

curl -X GET https://<AUTH_SERVER_HOST>/accounts/api/organizations/<ORG_ID>/environments \
  -H "Authorization: Bearer <BEARER_TOKEN>"

The response includes output similar to:

"environments": [
  {
    "id": "ENV_ID",
    "name": "Production",
    "organizationId": "ORG_ID",
  },
]

Get the Region ID

To get the region ID (REGION_ID):

curl "https://anypoint.mulesoft.com/mq/admin/api/v1/organizations/<ORG_ID>/environments/<ENV_ID>/regions"

The response includes output similar to:

 {
    "id": "us-east-1",
    "name": "US East",
    "type": "aws"
  },

Get the Queue ID

To get the queue ID (QUEUE_ID):

curl -X GET \
  https://anypoint.mulesoft.com/mq/admin/api/v1/organizations/<ORG_ID>/environments/<ENV_ID>/regions/<REGION_ID>/destinations \
  -H "Authorization: Bearer <BEARER_TOKEN>"

The response includes output such as:

{
  "encrypted" : true,
  "type" : "queue",
  "queueId" : "myDemoQueue",
  "maxDeliveries" : 10,
  "deadLetterQueueId" : "myDLQ",
  "fifo" : false,
  "isFallback" : false,
  "defaultTtl" : 604800000,
  "defaultLockTtl" : 120000,
  "defaultDeliveryDelay" : 0
},

Anypoint MQ Admin API

The Anypoint MQ Admin API provides access to Anypoint MQ administrative functionality.

You can use the Anypoint MQ Admin API to create and manage queues, message exchanges, and client apps.

If you call the Anypoint MQ Admin API for distinct environments within one minute, the API throttles your requests to 50 transactions per minute (TPM).

These examples use the Anypoint MQ Admin API to create queues and message routing rules from the command line using curl:

Create a FIFO Queue

You can create a FIFO queue using the Anypoint MQ Admin API by including the "fifo": true field.

The organization from which you use the Administration portal must have an Anypoint MQ FIFO entitlement. See Anypoint MQ FAQ for the regions where Anypoint MQ is available.

Use a curl command to create a FIFO queue:

curl -X PUT "https://anypoint.mulesoft.com/mq/admin/api/v1/organizations/<ORG_ID>/environments/<ENV_ID>/regions/<REGION_ID>/destinations/queues/<QUEUE_ID>" \
--header 'Content-Type: application/json' \
--header 'Authorization: bearer <BEARER_TOKEN>' \
--data-raw '{
  "defaultTtl" : 120000,
  "defaultLockTtl" : 10000,
  "encrypted" : false,
  "fifo" : true
}'

The response includes output such as:

{
  "encrypted" : true,
  "type" : "queue",
  "queueId" : "myDemoQueue-api",
  "maxDeliveries" : 10,
  "deadLetterQueueId" : "myDLQ-api",
  "fifo" : false,
  "isFallback" : false,
  "defaultTtl" : 604800000,
  "defaultLockTtl" : 120000,
  "defaultDeliveryDelay" : 0
},

Create or Change Message Routing Rules

To route a subset of the messages that are published to an exchange to a specific queue, use the Admin API to create message routing rules on the binding between the exchange and the queue.

The new message routing rule can take up to 15 minutes to take effect.

Any bindings without configured message routing rules continue to receive all messages from the exchange.

To create a message routing rule, use a curl command like this:

curl -X PUT "https://anypoint.mulesoft.com/mq/admin/api/v1/organizations/<ORG_ID>/environments/<ENV_ID>/regions/<REGION_ID>/bindings/exchanges/purchases/queues/premiumPurchases/rules/routing" \
--header 'Authorization: bearer <BEARER_TOKEN>' \
--header 'Content-Type: application/json' \
--data-raw '{
    "routingRules" : [{
        "propertyName" : "itemCategory",
        "propertyType" : "STRING",
        "matcherType" : "EQ",
        "value" : "premium"
    }]
}'

This message routing rule routes any message published to the purchases exchange that includes a property or header with the name itemCategory and the value premium to the premiumPurchases queue.

To change an existing routing rule, submit another PUT request with the new message routing rule configuration. A PUT request replaces the existing message routing rule on the binding with the new rule. Any changes or additions to a message routing rule can take up to 15 minutes to take effect.

For information about:

Enable or Disable Failover on an Existing Standard Queue

When you enable failover for a queue, Anypoint MQ automatically creates a fallback queue in a fallback region. If a Mule app can’t reach an Anypoint MQ server in a region, it switches to the fallback queue to publish and consume messages. For information about situations that can cause a region to be considered unavailable, see Region Unavailability.

You must restart all applications consuming from or publishing to the queue after enabling or disabling failover.

Use this curl command to enable failover for an existing standard queue:

curl -X PUT 'https://anypoint.mulesoft.com/mq/admin/api/v1/organizations/<ORG_ID>/environments/<ENV_ID>/regions/<REGION_ID>/destinations/queues/<QUEUE_ID>/fallback' \
-H 'Authorization: bearer <BEARER_TOKEN>' \
-H 'Content-Type: application/json' \
-d '{
    "fallbackEnabled" : true
}'

Use this curl command to disable failover for an existing standard queue:

curl -X PUT 'https://anypoint.mulesoft.com/mq/admin/api/v1/organizations/<ORG_ID>/environments/<ENV_ID>/regions/<REGION_ID>/destinations/queues/<QUEUE_ID>/fallback' \
-H 'Authorization: bearer <BEARER_TOKEN>' \
-H 'Content-Type: application/json' \
-d '{
    "fallbackEnabled" : false
}'

Retrieve Queue Configuration

When you retrieve information about all destinations or a single queue, the response includes the failover configuration.

Use this curl command to get the list of destinations:

curl -X GET 'https://anypoint.mulesoft.com/mq/admin/api/v1/organizations/<ORG_ID>/environments/<ENV_ID>/regions/<REGION_ID>/destinations' \
-H 'Authorization: bearer <BEARER_TOKEN>'

Use this curl command to get details about a specific queue:

curl -X GET 'https://anypoint.mulesoft.com/mq/admin/api/v1/organizations/<ORG_ID>/environments/<ENV_ID>/regions/<REGION_ID>/destinations/queues/<QUEUE_ID>' \
-H 'Authorization: bearer <BEARER_TOKEN>'

The response from these commands includes output similar to this:

Primary Queue
[
{
    "encrypted" : true,
    "type" : "queue",
    "queueId" : "00-test",
    "fifo" : false,
    ...
    "isFallback" : false,                 (1)
    "fallbackConfig" : {
        "enabled" : true,                 (2)
        "linkedQueueName" : "00-test_fb", (3)
        "linkedQueueRegion" : "us-west-2" (4)
    }
},
]
1 This queue is a primary queue.
2 Failover is enabled for this queue.
3 The fallback queue for this queue is 00-test_fb. If the primary region goes down, apps publish and consume from this queue.
4 The fallback region for this queue is us-west-2.
Fallback Queue
[
{
    "encrypted" : true,
    "type" : "queue",
    "queueId" : "test_fb",
    "fifo" : false,
    ...
    "isFallback" : true,                     (1)
    "fallbackConfig" : {
        "enabled" : true,                    (2)
        "linkedQueueName" : "test",          (3)
        "linkedQueueRegion" : "ca-central-1" (4)
    }
},
]
1 This queue is a fallback queue.
2 Failover is enabled. If the primary region goes down, apps publish and consume from this queue.
3 The primary queue that is linked to this fallback queue is test.
4 The region for the primary queue that is linked to this fallback queue is ca-central-1.
Standard Queue Without Failover Configured

The response includes "isFallback" : false and doesn’t include fallbackConfig.

[
  {
  "encrypted" : true,
  "type" : "queue",
  "queueId" : "hello1",
  "fifo" : false,
  ...
  "isFallback" : false  (1)
},
]
1 This queue is a primary queue.
FIFO Queue

The response doesn’t include fallbackConfig because FIFO queues don’t support failover.

{
  "encrypted" : true,
  "type" : "queue",
  "queueId" : "hello1",
  "fifo" : true,       (1)
  ...
  "isFallback" : false
},
]
1 This queue is a FIFO queue, which doesn’t support failover.
Exchange

The response doesn’t include fallbackConfig because exchanges don’t support failover.

[
{
  "encrypted" : true,
  "type" : "exchange",  (1)
  "exchangeId" : "hello1"
}
]
1 This queue is a message exchange, which doesn’t support failover.

Anypoint MQ Broker API

The Anypoint MQ Broker API enables clients to publish, consume, route, and acknowledge messages from queues and message exchanges.

You can get the organization ID and environment ID in the payload.txt file that Anypoint Platform creates for any auditable action in MQ. See Anypoint MQ Audit Logging.

These examples use the Anypoint MQ Broker API to publish and consume messages and to test Anypoint MQ from the command line using curl.

For the regions where Anypoint MQ and FIFO are available, see Anypoint MQ Regions.

Send a Message

This curl command publishes a message:

curl -X PUT "https://mq-us-east-1.anypoint.mulesoft.com/api/v1/organizations/<ORG_ID>/environments/<ENV_ID>/destinations/postmanExchange/messages/552" \
-H "Content-Type: application/json" \
-H "Authorization: bearer <BEARER_TOKEN>" \
-H "Cache-Control: no-cache" \
-d '{
  "properties": {
    "userDefinedHeader": "User defined stuff",
    "anotherUserDefinedHeader": "Random stuff"
  },

  "body": "This is a message payload"
}'

Send a Message with Routing Properties

Anypoint MQ evaluates the configured message routing rules against all headers and properties attributes in the published messages.

This curl command publishes a message with the value of the itemCategory property as premium. The message routing rule on the purchases exchange binding (set up in Create or Change Message Routing Rules) routes the message to the premiumPurchases queue.

curl -X PUT "https://mq-us-east-1.anypoint.mulesoft.com/api/v1/organizations/<ORG_ID>/environments/<ENV_ID>/destinations/postmanExchange/messages/552" \
-H "Content-Type: application/json" \
-H "Authorization: bearer <BEARER_TOKEN>" \
-H "Cache-Control: no-cache" \
-d '{ \
  "properties": {
    "itemCategory": "premium",
  },
  "headers": {
    "itemSize": "large"
  },
  "body": "This is a message payload"
}'

For information about the message routing rule requirements, see Requirements and Restrictions.

Retrieve a Message

This curl command gets a message:

curl -X GET "https://mq-us-east-1.anypoint.mulesoft.com/api/v1/organizations/<ORG_ID>/environments/<ENV_ID>/destinations/postmanQueue/messages?pollingTime=10000&batchSize=1&lockTtl=10000" \
-H "Authorization: bearer <BEARER_TOKEN>" \
-H "Cache-Control: no-cache"

You can control whether to show the message payload in the response using the payloadVisibility query parameter. This parameter is useful when retrieving large payloads.

The payloadVisibility parameter takes these options:

  • full: Shows the message payload in the response.
    This option is the default.

  • none: Hides the message payload in the response.

  • conditional: Hides the message payload if the payload size is larger than 1 MB.

If the payload is hidden because payloadVisibility is set to none or conditional, the response includes payloadHidden=true in the message header.

This curl command gets a message and payload, displaying the payload only if the payload size is smaller than 1 MB:

curl -X GET "https://mq-us-east-1.anypoint.mulesoft.com/api/v1/organizations/<ORG_ID>/environments/<ENV_ID>/destinations/postmanQueue/messages?pollingTime=10000&batchSize=1&lockTtl=10000&payloadVisibility=conditional" \
-H "Authorization: bearer <BEARER_TOKEN>" \
-H "Cache-Control: no-cache"

Anypoint MQ Stats API

The Anypoint MQ Stats API enables you to get statistics and metrics for queues and message exchanges.

You can use the Anypoint MQ Stats API to perform statistical analysis of queue performance.

Use the Stats API to retrieve:

For more information, see the Anypoint MQ Stats API in the MuleSoft developer portal.
The query parameters must be URL-encoded to preserve their values. For example, you must URL-encode a startDate of 2024-07-11T17:51:54.000Z to 11T17%3A51%3A54.000Z before sending it in the query.

Get Current Statistics for Queues

You can get a snapshot of the number of messages in the queue and how many are in-flight. See Anypoint MQ Glossary for a definition of in-flight messages. The data updates in almost real-time.

Stats API responses and message status changes include up to 60 seconds of inconsistency due to internal post-processing activities. Message status changes include from in-queue to in-flight, from in-flight to in-queue, and from in-flight to deleted. For this reason, don’t use the Stats API for syncing processing actions, such as checking if the queue is empty.

The Stats API can fetch statistics for multiple queues and returns a comma-separated list.

/queues?destinationIds={queue1},{queue2}

Sample Request and Response:

Use this curl command to get current statistics for a queue:

curl -X GET "https://anypoint.mulesoft.com/mq/stats/api/v1/organizations/<ORG_ID>/environments/<ENV_ID>/regions/REGION_ID/queues?destinationIds=DESTINATION_ID" \
-H "Authorization: bearer <BEARER_TOKEN>" \
-H "Cache-Control: no-cache"

This command returns output similar to:

 {
    "destination": "95bgpyxYsVyFE",
    "messages": 0,
    "inflightMessages": 0
 }

Get Historical Statistics for a Queue

Use this API to fetch historical statistics for a queue. Statistics don’t get updated in real-time, and there is an approximate latency of five to ten minutes before data is published. The retention period of historical data is 15 months. To limit the volume of data, historical data is stored at reduced levels of granularity:

  • Data points with a period of fewer than 60 seconds are available for three hours.

  • One-minute data points are available for 15 days.

  • Five-minute data points are available for 63 days.

  • One-hour data points are available for 15 months.

/queues/{queueId}?startDate=…​&endDate=…​&period=…​

Sample Request and Response:

Use this curl command to get historical statistics for a queue:

curl -X GET "https://anypoint.mulesoft.com/mq/stats/api/v1/organizations/<ORG_ID>/environments/<ENV_ID>/regions/REGION_URL/queues/95bgpyxYsVyFE?startDate=Thursday%2C%208%20Nov%202024%2004%3A49%3A37%20GMT%26endDate%3DSun%2C%2011%20Nov%202024%2004%3A60%3A44%20GMT%26period%3D600" \
-H "Authorization: bearer <BEARER_TOKEN>" \
-H "Cache-Control: no-cache"

This command returns output similar to:

  {
    "destination": "95bgpyxYsVyFE",
    "messages": [
        {
            "date": "2024-11-08T04:59:37.000+0000",
            "value": 0
        },
        {
            "date": "2024-11-08T05:09:37.000+0000",
            "value": 0
        }
    ]
  }

The duration is an integer and is the granularity of data points in seconds.

Get Historical Statistics for Exchanges

Retention policies are the same as in the previous Get Historical Statistics for a Queue section.

/exchanges/{exchangeId}?startDate=…​&endDate=…​&period=…​

Sample Request and Response:

Use this curl command to get historical statistics for an exchange:

curl -X GET "https://anypoint.mulesoft.com/mq/stats/api/v1/organizations/<ORG_ID>/environments/<ENV_ID>/regions/REGION_URL/exchanges/exchange-test?startDate=Wed%2C%2014%20Nov%202024%2021%3A53%3A08%20GMT&endDate=Wed%2C%2014%20Nov%202024%2022%3A53%3A08%20GMT&period%3D600" \
-H "Authorization: bearer <BEARER_TOKEN>" \
-H "Cache-Control: no-cache"

This command returns output similar to:

{
    "destination": "exchange-test",
    "messagesPublished": [
        {
            "date": "2024-11-14T21:59:08.000+0000",
            "value": 0
        }
     ]
}

The period is an integer and is the granularity of data points in seconds.

Get Usage Metrics by Environment

Only the US Cloud and EU Cloud instances of Anypoint Platform support this REST API.

You can use the Stats API to retrieve Anypoint MQ usage information by environment for a particular organization:

/environments/<ENV_ID>?startDate=…​&endDate=…​&period=…​

This information is not real-time and has a latency.

Sample Request and Response:

Use this curl command to get usage metrics by environment:

curl -X GET "https://anypoint.mulesoft.com/mq/stats/api/v1/organizations/<ORG_ID>/environments/<ENV_ID>?startDate=Thursday%2C%208%20Nov%202024%2004%3A49%3A37%20GMT%26endDate%3DSun%2C%2011%20Nov%202024%2004%3A60%3A44%20GMT%26period%3D1day%0A" \
-H "Authorization: bearer <BEARER_TOKEN>" \
-H "Cache-Control: no-cache"

This command returns output similar to:

  {
    "timestamp": "2024-11-08T00:00Z",
    "apiRequestCount": 127,
    "messageReceiptCount": 11,
    "billableUnitCount": 11,
    "messageByteCount": 6148
  }

The apiRequestCount returns the number of API requests made to the Anypoint MQ service during the specified period.

All requests to the Anypoint MQ Broker API count against your monthly quota. Requests include sending, receiving, and acknowledging messages and operations on queues and exchanges.

For more information about Anypoint MQ billing, see Viewing Anypoint MQ Usage Data.

Anypoint MQ doesn’t use messageReceiptCount and billableUnitCount for billing, and you can safely ignore them. Anypoint MQ uses messageReceiptCount to determine the message units displayed on the MQ Usage page; billableUnitCount is an internally used value set to the same value as messageReceiptCount.

Get Usage Metrics by Organization

Only the US Cloud and EU Cloud instances of Anypoint Platform support this REST API.

You can use the Stats API to retrieve Anypoint MQ usage for the root business organization:

/organizations/<ORG_ID>?startDate=…​&endDate=…​&period=…​

Sample Request and Response:

Use this curl command to get daily usage metrics by organization for a month:

curl -X GET "https://anypoint.mulesoft.com/mq/stats/api/v1/organizations/<ORG_ID>?startDate=Sun%2C%201%20Oct%202024%2004%3A49%3A37%20GMT%26endDate%3DTue%2C%2031%20Oct%202024%2004%3A50%3A44%20GMT%26period%3D1day" \
-H "Authorization: bearer <BEARER_TOKEN>" \
-H "Cache-Control: no-cache"

This command returns output similar to:

  {
    "timestamp": "2024-10-31T00:00Z",
    "apiRequestCount": 1066,
    "messageReceiptCount": 194,
    "billableUnitCount": 194,
    "messageByteCount": 107048
  }

The apiRequestCount returns the number of API requests made to the Anypoint MQ service during the specified period.

All requests to the Anypoint MQ Broker API count against your monthly quota. Requests include sending, receiving, and acknowledging messages and operations on queues and exchanges.

For more information about Anypoint MQ billing, see Viewing Anypoint MQ Usage Data.

Anypoint MQ doesn’t use messageReceiptCount and billableUnitCount for billing, and you can safely ignore them. Anypoint MQ uses messageReceiptCount to determine the message units displayed on the MQ Usage page; billableUnitCount is an internally used value set to the same value as messageReceiptCount.

Example: Anypoint MQ Stats API

To access the Anypoint MQ Stats API, you must first authenticate using the Access Management API.

These statistics are provided:

  • messagesVisible

    The number of messages that can be retrieved from a queue.

  • messagesSent

    The number of messages added to a queue.

  • messagesReceived

    The number of messages received in a queue.

  • messagesAcked

    The number of acknowledged messages, including any messages deleted using the Anypoint Platform > MQ user interface.

Example request to list statistics for July 26 to July 28, 2024:

curl -X GET "https://anypoint.mulesoft.com/mq/stats/api/v1/organizations/<ORG_ID>/environments/<ENV_ID>/regions/REGION_URL/queues/randomQueue/?startDate=Thu%2C%2026%20Jul%202024%2000%3A00%3A00%20GMT&endDate=Sat%2C%2028%20Jul%202024%2020%3A00%3A00%20GMT&period%3D600" \
-H "authorization: Bearer <BEARER_TOKEN>" \
-H "cache-control: no-cache"

This command returns output similar to:

{
  "destination": "myDestination",
  "messages": [
    {
      "date": "2024-07-26T00:00:00.000+0000",
      "value": 2126
    },
    {
      "date": "2024-07-27T00:00:00.000+0000",
      "value": 2126
    },
    {
      "date": "2024-07-28T00:00:00.000+0000",
      "value": 587
    }
  ],
  "inflightMessages": [
    {
      "date": "2024-07-26T00:00:00.000+0000",
      "value": 0
    },
    {
      "date": "2024-07-27T00:00:00.000+0000",
      "value": 0
    },
    {
      "date": "2024-07-28T00:00:00.000+0000",
      "value": 0
    }
  ],
  "messagesVisible": [
    {
      "date": "2024-07-26T00:00:00.000+0000",
      "value": 2126
    },
    {
      "date": "2024-07-27T00:00:00.000+0000",
      "value": 2126
    },
    {
      "date": "2024-07-28T00:00:00.000+0000",
      "value": 587
    }
  ],
  "messagesSent": [
    {
      "date": "2024-07-26T00:00:00.000+0000",
      "value": 0
    },
    {
      "date": "2024-07-27T00:00:00.000+0000",
      "value": 0
    },
    {
      "date": "2024-07-28T00:00:00.000+0000",
      "value": 0
    }
  ],
  "messagesReceived": [
    {
      "date": "2024-07-26T00:00:00.000+0000",
      "value": 0
    },
    {
      "date": "2024-07-27T00:00:00.000+0000",
      "value": 0
    },
    {
      "date": "2024-07-28T00:00:00.000+0000",
      "value": 0
    }
  ],
  "messagesAcked": [
    {
      "date": "2024-07-26T00:00:00.000+0000",
      "value": 0
    },
    {
      "date": "2024-07-27T00:00:00.000+0000",
      "value": 0
    },
    {
      "date": "2024-07-28T00:00:00.000+0000",
      "value": 0
    }
  ]
}

Create Queues and Exchanges with Groovy

To create queues and exchanges programatically, you can use a language such as groovy.

This example consists of the cloudhub.properties file in which you list the queues and exchanges to create, and a script file that references the properties file.

Date Format

Anypoint MQ lets you specify start and end dates for the Stats API in standard ISO 8601 format.

For example: 2018-10-23T13:00:00Z

Invoke a Command

After modifying the properties file for access to your Anypoint Platform account, use this command to start the script file:

groovy <program_name>.groovy

Configure a Properties File

This example properties file defines the access credentials, organization ID, environment ID, region ID, and the names of the queues and exchanges to create:

username="<anypoint_platform_username>"
password="<anypoint_platform_password>"
organizationID="ORG_ID"
environmentID {
    development="DEVELOPMENT_ENV_ID"
    qa="QA_ENV_ID"
    staging="STAGING_ENV_ID"
    production="PRODUCTION_ENV_ID"
}
regionID="REGION_URL"

queues=[
    "Queue1",
    "Queue2",
    "QueueN",
]

exchanges=[
    "Exchange1",
    "Exchange2",
    "ExchangeN"
]

For the regions where Anypoint MQ and FIFO queues are available, see Anypoint MQ Regions.

Create a Script File

This example script creates the queues and exchanges listed in the properties file:

package guru.oso.mule

@Grab(group = 'org.apache.httpcomponents', module = 'httpclient', version = '4.5.3')

import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.client.methods.HttpPut
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClientBuilder

class AnypointMQAdminClient {

  static String HOST = "https://anypoint.mulesoft.com"

    static void main(String[] args) {

        def props

        if (args) {
            props = new ConfigSlurper().parse(new File(args[0]).toURI().toURL())
        } else {
            props = new ConfigSlurper().parse(new File("cloudhub.properties").toURI().toURL())
        }

        def ENV_ID = props.environmentID.production
        def token = authenticate(props.username, props.password)
        retrieveDestinations(props, token, ENV_ID)
    }

    static authenticate(String username, String password) {

      // build JSON
        def map = [:]
        map["username"] = username
        map["password"] = password
        def jsonBody = new JsonBuilder(map).toString()

        // build HTTP POST
        def url = HOST + '/accounts/login'
        def post = new HttpPost(url)

        post.addHeader("Content-Type", "application/json")
        post.setEntity(new StringEntity(jsonBody))

        // execute
        def client = HttpClientBuilder.create().build()
        def response = client.execute(post)

        // read and print response
        def bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
        def jsonResponse = bufferedReader.getText()
        println "Response: \n" + jsonResponse

        // parse and return token
        def slurper = new JsonSlurper()
        def resultMap = slurper.parseText(jsonResponse)

        return resultMap["access_token"]
    }

    static retrieveDestinations(ConfigObject props, String token, String ENV_ID) {

        def ORG_ID = props.organizationID
        def REGION_URL = props.regionID

        // build HTTP GET
        def getDestinationsURL = HOST + '/mq/admin/api/v1/organizations/' + ORG_ID +
          '/environments/' + ENV_ID + '/regions/' + REGION_URL + '/destinations'
        def getDestinations = new HttpGet(getDestinationsURL)

        // set token
        getDestinations.setHeader("Authorization", "Bearer " + token)

        // execute
        def client = HttpClientBuilder.create().build()
        def response = client.execute(getDestinations)

        // parse and print results
        def bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
        def jsonResponse = bufferedReader.getText()
        println "Response: \n" + jsonResponse
    }

    static retrieveQueue(ConfigObject props, String token, String ENV_ID, String QUEUE_ID) {

        def ORG_ID = props.organizationID
        def REGION_URL = props.regionID

        // build HTTP GET
        def getQueueURL = HOST + '/mq/admin/api/v1/organizations/' + ORG_ID + '/environments/' +
          ENV_ID + '/regions/' + REGION_URL + '/destinations/queues/' + QUEUE_ID
        def getQueue = new HttpGet(getQueueURL)

        // set token
        getQueue.addHeader("Authorization", "Bearer " + token)

        // execute
        def client = HttpClientBuilder.create().build()
        def response = client.execute(getQueue)

        // parse and print results
        def bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
        def jsonResponse = bufferedReader.getText()
        println "Response: \n" + jsonResponse
    }

    static createQueues(ConfigObject props, String token, String ENV_ID) {

        def ORG_ID = props.organizationID
        def REGION_URL = props.regionID
        def queues = props.queues

        queues.each { QUEUE_ID ->

            def putQueueURL = HOST + '/mq/admin/api/v1/organizations/' + ORG_ID + '/environments/' +
              ENV_ID + '/regions/' + REGION_URL + '/destinations/queues/' + QUEUE_ID
            def putQueue = new HttpPut(putQueueURL)

            putQueue.addHeader("Content-Type", "application/json")
            putQueue.addHeader("Authorization", "Bearer " + token)

            def queueMap = [:]
            queueMap["defaultTtl"] = 604800000
            queueMap["defaultLockTtl"] = 120000
            queueMap["encrypted"] = false
            queueMap["fifo"] = false

            def putQueueJSONBody = new JsonBuilder(queueMap).toString()
            putQueue.setEntity(new StringEntity(putQueueJSONBody))

            def client = HttpClientBuilder.create().build()
            def response = client.execute(putQueue)

            def bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
            def jsonResponse = bufferedReader.getText()
            println "Response: \n" + jsonResponse
        }
    }

    static createExchanges(ConfigObject props, String token, String ENV_ID) {

        def ORG_ID = props.organizationID
        def REGION_URL = props.regionID

        def exchanges = props.exchanges

        exchanges.each { exchangeID ->

            def putExchangeURL = HOST + '/mq/admin/api/v1/organizations/' + ORG_ID + '/environments/' + ENV_ID + '/regions/' + REGION_URL + '/destinations/exchanges/' + EXCHANGE_ID
            def putExchange = new HttpPut(putExchangeURL)

            putExchange.addHeader("Content-Type", "application/json")
            putExchange.addHeader("Authorization", "Bearer " + token)

            def exchangeMap = [:]
            exchangeMap["encrypted"] = false

            def putExchangeJSONBody = new JsonBuilder(exchangeMap).toString()
            putExchange.setEntity(new StringEntity(putExchangeJSONBody))

            def client = HttpClientBuilder.create().build()
            def response = client.execute(putExchange)

            def bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
            def jsonResponse = bufferedReader.getText()
            println "Response: \n" + jsonResponse
        }
    }
}

Test Anypoint MQ from Postman, Studio, and a Browser

This example enables you to test Anypoint MQ from Postman, Anypoint Studio, and a browser:

Set Up Postman

The Postman app provides a platform for accessing the Anypoint MQ APIs. After downloading and installing Postman, supply this information to create an environment:

  • ORG_ID

  • ENV_ID

  • Bearer (Authentication) Token

  • Host ID (from Anypoint Platform/Anypoint MQ)

  • Client ID (from Anypoint Platform/Anypoint MQ)

  • Client Secret (from Anypoint Platform/Anypoint MQ)

  • Queue name (you can set this queue name in Postman)

After you authorize access to an Anypoint MQ API, you can then publish a message, consume the message, and get the lock ID from the returned information in the body.

For example, this information is returned from the consume (GET) command:

{
    "properties": {
      "anotherUserDefinedHeader": "Random stuff",
      "userDefinedHeader": "User defined stuff"
    },
    "headers": {
      "messageId": "514",
      "lockId": "<lockIDvalue>",
      "created": "Tue, 23 Oct 2018 21:17:57 GMT",
      "deliveryCount": "2"
    },
    ...
}

After you have the lock ID, you can add it to your Postman environment to facilitate future requests.

Set Up Studio for API Access

Anypoint Studio enables you to create a Mule app that uses the Anypoint MQ connector. This section summarizes the steps.

You can set up a Studio project with:

  • An HTTP connector:

    • Host 0.0.0.0

    • Port 8081

    • Path in the properties menu set to /mq/{messageId}.

  • Anypoint MQ connector with the client ID and client secret from Anypoint Platform > MQ, and the Destination set to the queue you created in Postman.

  • Logger with Message set to the \#[payload] value.

    1. Right-click the project name in the Package Explorer window and click Run As > Mule Application.

      Ensure that the Console messages end with the DEPLOYED value.

    2. In Postman, publish a new message.

Use a Browser to Access

After you set up an HTTP Listener in Studio, browse to the address 0.0.0.0:8081. The browser displays the message sent by Postman, which the Anypoint MQ connector received, and the HTTP connector sent to the browser.

Download Anypoint MQ APIs from Exchange

To download the Anypoint MQ APIs from Exchange, click Download and select the format to download: RAML, OAS, or as a connector file for Mule 3 or Mule 4.

Download option for Anypoint MQ Admin API in Exchange