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

The following example with the Broker API illustrates the workflow for accessing an API:

mq api workflow

Steps:

  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.

Authorize API Access

Before accessing an API, you must get an access token:

To use a connected app with the Anypoint MQ REST APIs, see Authorize API Access for Connected Apps.

The curl command for each is explained in the API sections.

Authorize API Access for Connected Apps

To use a connected app with the Anypoint MQ REST APIs, see:

The /authorize endpoints in the Anypoint MQ Admin API and Anypoint MQ Broker API do not support connected apps. You can’t use tokens obtained from those endpoints to access a connected app.

Anypoint MQ Admin API

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

You can use the 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:

Get the Access Token

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

To use the Admin API, you can get the access token from the Anypoint Platform user. The access token is also known as the Bearer. The default time to live (TTL) for the access token is 60 minutes.

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 MQ Audit Logging.

Use a curl command like the following to get the access token:

curl -X POST "https://anypoint.mulesoft.com/accounts/login" \
-H "Content-Type: application/json" \
-d '{"username":"USERNAME", "password":"PASSWORD"}'

This command returns output similar to:

{
  "access_token": "42424242-4242-4242-4242-424242424242",
  "token_type": "bearer",
  "redirectUrl": "/home/"
}

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 like the following to create a FIFO queue:

curl -X PUT "https://anypoint.mulesoft.com/mq/admin/api/v1/organizations/ORGANIZATION_ID/environments/ENVIRONMENT_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
}'

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 the following:

curl -X PUT "https://anypoint.mulesoft.com/mq/admin/api/v1/organizations/ORGANIZATION_ID/environments/ENVIRONMENT_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/ORGANIZATION_ID/environments/ENVIRONMENT_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/ORGANIZATION_ID/environments/ENVIRONMENT_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/ORGANIZATION_ID/environments/ENVIRONMENT_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/ORGANIZATION_ID/environments/ENVIRONMENT_ID/regions/REGION_ID/destinations/queues/QUEUE_ID' \
-H 'Authorization: bearer BEARER_TOKEN'

The response from these commands include output similar to the following:

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 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.

You must substitute the placeholder string, ORGANIZATION_ID with the proper values for authorization and token strings. These examples use Postman to access the queue.

See the Anypoint MQ FAQ for the regions where Anypoint MQ and FIFO are available.

Get the Broker API Access Token

Getting the access (bearer) token requires using either a command like curl or an app like Postman. The example that follows uses curl. If you are a Windows user, you must download a curl command before accessing the information.

The access token in this section can only be used with the Broker API. Do not use this access token with the Stats and Admin APIs.

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 Broker API access token:

  1. Sign in to Anypoint Platform.

  2. Click MQ > Client Apps, and then click the Add icon (Add icon in Client Apps) to create an app.

  3. Get the client ID and client secret and use these values in the following curl command replacing CLIENT_ID and CLIENT_SECRET:

    curl -X POST "https://anypoint.mulesoft.com/accounts/oauth2/token" \
    -H "Content-Type: application/json" \
    -d '{
        "client_id": "<CLIENT_ID>",
        "client_secret": "<CLIENT_SECRET>",
        "grant_type": "client_credentials"
    }'
  4. Submit the curl command.

    The command returns output similar to:

    {"access_token":"<token>","simple_client":{"envId":"ENVIRONMENT_ID","orgId":"ORGANIZATION_ID"},"token_type":"bearer"}

Send a Message

The following curl command publishes a message:

curl -X PUT "https://mq-us-east-1.anypoint.mulesoft.com/api/v1/organizations/ORGANIZATION_ID/environments/ENVIRONMENT_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.

The following 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/ORGANIZATION_ID/environments/ENVIRONMENT_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

The following curl command gets a message:

curl -X GET "https://mq-us-east-1.anypoint.mulesoft.com/api/v1/organizations/ORGANIZATION_ID/environments/ENVIRONMENT_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 the following 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.

The following 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/ORGANIZATION_ID/environments/ENVIRONMENT_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:

  • Anypoint MQ metrics:

    • Near real-time statistics for queues

    • Historical statistics for queues

    • Historical statistics for message exchanges

  • Usage metrics

    View your entire organization’s usage of Anypoint MQ for billing purposes:

    • Usage per environment

    • Usage per organization

  • Statistics for queues and message exchanges

  • Number of messages currently in a queue

The Anypoint MQ Stats API limits retrieving stats for the /organizations/{ORGANIZATION_ID} and /organizations/{ORGANIZATION_ID}/environments/{ENVIRONMENT_ID} endpoints to 10 transactions per minute (TPM).

If the requests exceed this limit, the Anypoint MQ Stats API returns an HTTP 429 status code.

For all other Anypoint MQ Stats API endpoints, the limit is 200 transactions per minute.

For more information, see the Anypoint MQ Stats API in the MuleSoft developer portal.

Get the Stats API Access Token

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

To use the Stats API, you can get the access token from the Anypoint Platform user. The access token is also known as the Bearer. The default time to live (TTL) for the access token is 60 minutes. 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.

Use this curl command to get the access token:

curl -X POST "https://anypoint.mulesoft.com/accounts/login" \
-H "Content-Type: application/json" \
-H "Cache-Control: no-cache" \
-d '{"username":"USERNAME", "password":"PASSWORD"}'

This command returns output similar to:

{
  "access_token": "42424242-4242-4242-4242-424242424242",
  "token_type": "bearer",
  "redirectUrl": "/home/"
}

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:

[source,bash]
curl -X GET "https://anypoint.mulesoft.com/mq/stats/api/v1/organizations/ORGANIZATION_ID/environments/ENVIRONMENT_ID/regions/REGION_URL/queues?destinationIds=DESTINATION_ID" \
-H "Authorization: bearer BEARER_TOKEN" \
-H "Cache-Control: no-cache"

This command returns output similar to:

[source,json,linenums]
 {
    "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/ORGANIZATION_ID/environments/ENVIRONMENT_ID/regions/REGION_URL/queues/95bgpyxYsVyFE?startDate=Thursday, 8 Nov 2018 04:49:37 GMT&endDate=Sun, 11 Nov 2018 04:60:44 GMT&period=600" \
-H "Authorization: bearer BEARER_TOKEN" \
-H "Cache-Control: no-cache"

This command returns output similar to:

  {
    "destination": "95bgpyxYsVyFE",
    "messages": [
        {
            "date": "2018-11-08T04:59:37.000+0000",
            "value": 0
        },
        {
            "date": "2018-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/ORGANIZATION_ID/environments/ENVIRONMENT_ID/regions/REGION_URL/exchanges/exchange-test?startDate=Wed%2C%2014%20Nov%202018%2021%3A53%3A08%20GMT&endDate=Wed%2C%2014%20Nov%202018%2022%3A53%3A08%20GMT&period=360" \
-H "Authorization: bearer BEARER_TOKEN" \
-H "Cache-Control: no-cache"

This command returns output similar to:

{
    "destination": "exchange-test",
    "messagesPublished": [
        {
            "date": "2018-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

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

/environments/ENVIRONMENT_ID?startDate=…​&endDate=…​&period=…​

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

The Anypoint MQ Stats API limits retrieving stats for the /organizations/{ORGANIZATION_ID} and /organizations/{ORGANIZATION_ID}/environments/{ENVIRONMENT_ID} endpoints to 10 transactions per minute (TPM).

If the requests exceed this limit, the Anypoint MQ Stats API returns an HTTP 429 status code.

For all other Anypoint MQ Stats API endpoints, the limit is 200 transactions per minute.

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/ORGANIZATION_ID/environments/ENVIRONMENT_ID?startDate=Thursday, 8 Nov 2021 04:49:37 GMT&endDate=Sun, 11 Nov 2021 04:60:44 GMT&period=1day" \
-H "Authorization: bearer BEARER_TOKEN" \
-H "Cache-Control: no-cache"

This command returns output similar to:

  {
    "timestamp": "2021-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 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 Usage Graphs.

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

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

/organizations/ORGANIZATION_ID?startDate=…​&endDate=…​&period=…​

The Anypoint MQ Stats API limits retrieving stats for the /organizations/{ORGANIZATION_ID} and /organizations/{ORGANIZATION_ID}/environments/{ENVIRONMENT_ID} endpoints to 10 transactions per minute (TPM).

If the requests exceed this limit, the Anypoint MQ Stats API returns an HTTP 429 status code.

For all other Anypoint MQ Stats API endpoints, the limit is 200 transactions per minute.

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/ORGANIZATION_ID?startDate=Sun, 1 Oct 2023 04:49:37 GMT&endDate=Tue, 31 Oct 2023 04:50:44 GMT&period=1day" \
-H "Authorization: bearer BEARER_TOKEN" \
-H "Cache-Control: no-cache"

This command returns output similar to:

  {
    "timestamp": "2023-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 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 Usage Graphs.

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, 2022:

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

This command returns output similar to:

{
  "destination": "myDestination",
  "messages": [
    {
      "date": "2018-07-26T00:00:00.000+0000",
      "value": 2126
    },
    {
      "date": "2018-07-27T00:00:00.000+0000",
      "value": 2126
    },
    {
      "date": "2018-07-28T00:00:00.000+0000",
      "value": 587
    }
  ],
  "inflightMessages": [
    {
      "date": "2018-07-26T00:00:00.000+0000",
      "value": 0
    },
    {
      "date": "2018-07-27T00:00:00.000+0000",
      "value": 0
    },
    {
      "date": "2018-07-28T00:00:00.000+0000",
      "value": 0
    }
  ],
  "messagesVisible": [
    {
      "date": "2018-07-26T00:00:00.000+0000",
      "value": 2126
    },
    {
      "date": "2018-07-27T00:00:00.000+0000",
      "value": 2126
    },
    {
      "date": "2018-07-28T00:00:00.000+0000",
      "value": 587
    }
  ],
  "messagesSent": [
    {
      "date": "2018-07-26T00:00:00.000+0000",
      "value": 0
    },
    {
      "date": "2018-07-27T00:00:00.000+0000",
      "value": 0
    },
    {
      "date": "2018-07-28T00:00:00.000+0000",
      "value": 0
    }
  ],
  "messagesReceived": [
    {
      "date": "2018-07-26T00:00:00.000+0000",
      "value": 0
    },
    {
      "date": "2018-07-27T00:00:00.000+0000",
      "value": 0
    },
    {
      "date": "2018-07-28T00:00:00.000+0000",
      "value": 0
    }
  ],
  "messagesAcked": [
    {
      "date": "2018-07-26T00:00:00.000+0000",
      "value": 0
    },
    {
      "date": "2018-07-27T00:00:00.000+0000",
      "value": 0
    },
    {
      "date": "2018-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.

The following 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

The following 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="ORGANIZATION_ID"
environmentID {
    development="DEVELOPMENT_ENVIRONMENT_ID"
    qa="QA_ENVIRONMENT_ID"
    staging="STAGING_ENVIRONMENT_ID"
    production="PRODUCTION_ENVIRONMENT_ID"
}
regionID="REGION_URL"

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

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

See the Anypoint MQ FAQ for the regions where Anypoint MQ and FIFO queues are available.

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 ENVIRONMENT_ID = props.environmentID.production
        def token = authenticate(props.username, props.password)
        retrieveDestinations(props, token, ENVIRONMENT_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 ENVIRONMENT_ID) {

        def ORGANIZATION_ID = props.organizationID
        def REGION_URL = props.regionID

        // build HTTP GET
        def getDestinationsURL = HOST + '/mq/admin/api/v1/organizations/' + ORGANIZATION_ID +
          '/environments/' + ENVIRONMENT_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 ENVIRONMENT_ID, String QUEUE_ID) {

        def ORGANIZATION_ID = props.organizationID
        def REGION_URL = props.regionID

        // build HTTP GET
        def getQueueURL = HOST + '/mq/admin/api/v1/organizations/' + ORGANIZATION_ID + '/environments/' +
          ENVIRONMENT_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 ENVIRONMENT_ID) {

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

        queues.each { QUEUE_ID ->

            def putQueueURL = HOST + '/mq/admin/api/v1/organizations/' + ORGANIZATION_ID + '/environments/' +
              ENVIRONMENT_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 ENVIRONMENT_ID) {

        def ORGANIZATION_ID = props.organizationID
        def REGION_URL = props.regionID

        def exchanges = props.exchanges

        exchanges.each { exchangeID ->

            def putExchangeURL = HOST + '/mq/admin/api/v1/organizations/' + ORGANIZATION_ID + '/environments/' + ENVIRONMENT_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:

  • ORGANIZATION_ID

  • ENVIRONMENT_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 Anypoint MQ APIs in Exchange