Contact Free trial Login

Anypoint MQ REST APIs

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

Anypoint MQ provides these APIs:

Anypoint MQ portals 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 application 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 application acknowledges the message and requests Anypoint MQ to delete the message, or the application negatively acknowledges the message and requests Anypoint MQ to make the message available to other applications. The application sends the message ID and lock ID to Anypoint MQ. For additional information on setting automatic ack or nack, see the Acknowledgment Mode guide.

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

Authorize API Access

Before accessing an API, you need to acquire an access token:

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

Anypoint MQ Admin API

  • Browse queues and message exchanges

  • Create queues and message exchanges

  • Manage bindings for message exchanges

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

You can get the access token from the Anypoint Platform user. The access token is also known as the Bearer. The access token has a default time to live (TTL) of 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.

You can use this curl command to get the access token:

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

The command returns output similar to:

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

Admin API - Create and manage applications, queues, and message exchanges.

In the Admin API portal, click Download to download the API as a RAML, Mule 3 zipped connector file, or as a Mule 4 connector JAR file.

mq rest admin portal

Create a FIFO Queue in the Admin API Portal

You can create a FIFO queue from the Admin API portal by including the "fifo": true field.

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

For the following path using the PUT operation:

/organizations/ORGANIZATION_ID/environments/ENVIRONMENT_ID/regions/REGION_ID/destinations/queues/QUEUE_ID

Use this body:

{
  "defaultTtl" : 120000,
  "defaultLockTtl" : 10000,
  "encrypted" : false,
  "fifo" : true
}

Anypoint MQ Broker API

This API lets you send and receive messages from queues and message exchanges.

The Anypoint MQ Broker API allows clients to send and receive messages from queues and 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.

Getting the access (bearer) token requires using either a command like curl or an application like Postman. The example that follows uses curl. If you are a Windows user, you need to 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.

To get the Broker API access token:

  1. Log into Anypoint Platform.

  2. Click MQ, Client Apps, and click the blue plus-circle icon to create an app.

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

    curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "client_id=CLIENT_ID&client_secret=CLIENT_SECRET&grant_type=client_credentials" "https://mq-us-east-1.anypoint.mulesoft.com/api/v1/authorize"

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

  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"}

Broker API Portal - Publish, consume, ack, and nack messages between queues and message exchanges.

In the Broker API portal, click Download to download the API as a RAML, Mule 3 zipped connector file, or as a Mule 4 connector JAR file.

mq rest broker portal

Anypoint MQ Stats API

Use cases:

  • Anypoint MQ metrics:

    • Real time statistics for queues

    • Historic statistics for queues

    • Historic statistics for message exchanges

  • Usage metrics - View your entire organization’s usage of Anypoint MQ for billing purposes:

    • Usage per environment

    • Usage per organization

  • Browse statistics for queues and message exchanges

  • View the number of messages currently in a queue

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

Use the Anypoint MQ Stats API

To access the Anypoint MQ Stats API, you must first authenticate using the Anypoint 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 access token has a default time to live (TTL) of 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.

You can use this curl command to get the access token:

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

This returns output similar to:

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

Anypoint MQ Stats API - Perform statistical analysis of queue performance.

In the Stats API portal, click Download to download the API as a RAML, Mule 3 zipped connector file, or as a Mule 4 connector JAR file.

mq rest stats portal

Real Time Statistics for Queues

You can get an immediate snapshot of how many messages are in the queue and how many are in-flight (see Anypoint MQ Terminology for what in-flight messages are). This data is updated in near real-time. The Statistics API can fetch real time statistics for multiple queues, and returns a comma separated list.

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

Sample Request and Response:

https://anypoint.mulesoft.com/mq/stats/api/v1/organizations/ORGANIZATION_ID/environments/ENVIRONMENT_ID/regions/REGION_URL
/queues?destinationIds=DESTINATION_ID

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

Historic Statistics for a Queue

This API can be used to fetch historic stats for a queue, however it does not get updated in real-time, and there is an approximate latency of 5 to 10 minutes before data is published. The retention period of historical data is 15 months. Also, to keep the volume of data under control, historical data is stored at reduced levels of granularity. Data points with a period of less than 60 seconds are available for 3 hours, one minute data points are available for 15 days, five minute data points for 63 days, and one hour data points for 15 months.

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

Sample Request and Response:

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

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

Historic Statistics for Exchanges

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

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

Sample Request and Response:

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

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

Note that period is an integer here. It’s the granularity of data points in seconds.

Usage Metrics by Environment

The Stats API can be used to sum up the usage for Anypoint MQ across all environments for a particular organization. This is not real time and has a latency.

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

Sample Request and Response:

https://anypoint.mulesoft.com/mq/stats/api/v1/organizations/ORGANIZATION_ID/environments/ENVIRONMENT_ID
?startDate=Thursday, 8 Nov 2018 04:49:37 GMT
&endDate=Sun, 11 Nov 2018 04:60:44 GMT
&period=1day

[
    {
        "timestamp": "2018-11-08T00:00Z",
        "apiRequestCount": 0,
        "messageReceiptCount": 0,
        "billableUnitCount": 0,
        "messageByteCount": 0
    }
]

Usage Metrics by Organization

The Stats API can be used to sum up the usage for Anypoint MQ across the master business organization:

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

Sample Request and Response:

https://anypoint.mulesoft.com/mq/stats/api/v1/organizations/ORGANIZATION_ID?
startDate=Thursday, 8 Nov 2018 04:49:37 GMT
&endDate=Sun, 11 Nov 2018 04:60:44 GMT
&period=1day

[
    {
        "timestamp": "2018-11-08T00:00Z",
        "apiRequestCount": 0,
        "messageReceiptCount": 0,
        "billableUnitCount": 0,
        "messageByteCount": 0
    }
]

Example: Anypoint MQ Stats API

To access the Anypoint MQ Stats API, you must first authenticate using the Anypoint 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 messages ACKed. Also includes any messages deleted using the Anypoint Platform > MQ user interface.

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

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%202018%2000%3A00%3A00%20GMT&endDate=Sat%2C%2028%20Jul%202018%2020%3A00%3A00%20GMT&period=600' \
  -H 'authorization: Bearer BEARER_TOKEN' \
  -H 'cache-control: no-cache' \
  -H 'postman-token: ACCESS_TOKEN'

Example response:

{
  "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
    }
  ]
}

Example: Groovy - Create Queues and Exchanges

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

The following example consists of the cloudhub.properties file where you list the queues and exchanges to create, and a script file that references the properties file.

Dates

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 MQ FAQ for the regions that Anypoint MQ and FIFO are available in.

Create a Script File

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

Example: Broker API Publish a Message

This example lets you test Anypoint MQ from the command line using curl. This example uses the MQ Broker API to publish and consume messages. You need to substitute the placeholder string, 42544254-4254-4254-4254-425442544254 for the proper values for authorization and token strings. These examples use Postman to access the queue.

The following curl command publishes a message:

curl -X PUT -H "Content-Type: application/json" \
-H "Authorization: bearer 42544254-4254-4254-4254-425442544254" \
-H "Cache-Control: no-cache" \
-H "Postman-Token: 42544254-4254-4254-42544254-425442544254" \
-d '{ \
  "properties": {
    "userDefinedHeader": "User defined stuff",
    "anotherUserDefinedHeader": "Random stuff"
  },

  "body": "This is a message payload"
}
' "https://mq-us-east-1.anypoint.mulesoft.com/api/v1/organizations/42544254-4254-4254-4254-425442544254/environments/42544254-4254-4254-4254-425442544254/destinations/postmanExchange/messages/552"

The following curl command gets a message:

curl -X GET -H "Authorization: bearer 42544254-4254-4254-4254-425442544254" \
-H "Cache-Control: no-cache" \
-H "Postman-Token: 42544254-4254-4254-4254-425442544254" \
"https://mq-us-east-1.anypoint.mulesoft.com/api/v1/organizations/42544254-4254-4254-4254-425442544254/environments/42544254-4254-4254-4254-425442544254/destinations/postmanQueue/messages?pollingTime=10000&batchSize=1&lockTtl=10000"

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

Example: Postman, Studio, and Browser

This example lets you test Anypoint MQ from a combination of Postman, Anypoint Studio, and a browser.

This example lets you access the Anypoint MQ APIs from these products:

Set Up Postman

The Postman application 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/MQ)

  • Client ID (from Anypoint Platform/MQ)

  • Client Secret (from Anypoint Platform/MQ)

  • A queue name - You can set this queue name in Postman

After you are able to authorize access to an Anypoint MQ API, 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 lets you create a Mule application that uses the Anypoint MQ connector. The steps in this section are summarized.

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.

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.

Go back to Postman and publish a new message.

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

See Also

Was this article helpful?

💙 Thanks for your feedback!

Edit on GitHub