3.3 Accessing Event Metadata, Inbound Attributes & Context Properties

Key Takeaways

  • In DataWeave 2.0, event components are accessed directly via keywords: `payload`, `attributes`, and `vars`.
  • Bracket notation (e.g., `attributes.headers['Content-Type']` or `attributes.queryParams['order-id']`) is required when metadata keys contain hyphens, dots, or special characters.
  • System and application properties are retrieved using context objects such as `app.name`, `server.dateTime`, `server.host`, `mule.version`, and configuration property functions like `p('db.port')`.
  • The Mule 4 `error` object provides structured diagnostic attributes including `error.description`, `error.detailedDescription`, `error.errorType.namespace`, `error.errorType.identifier`, and `error.childErrors`.
  • Defensive DataWeave navigation utilizing safe navigation (`?.`) and default operators (`default`) prevents null pointer exceptions when accessing optional query parameters, headers, or nested payload elements.
Last updated: August 2026

3.3 Accessing Event Metadata, Inbound Attributes & Context Properties

DataWeave 2.0 is the native expression language of Mule 4, tightly integrated into every connector configuration, XML attribute, router, and transformation script. Whether routing an event based on an incoming query parameter, extracting a bearer token from an authorization header, reading server timestamps for audit logs, or parsing an error payload, developers must know how to precisely navigate the Mule Event context.


1. Accessing Core Event Components in DataWeave

DataWeave exposes the active Mule Event through predefined top-level context keywords:

+-----------------------------------------------------------------------------+
|                     DATAWEAVE 2.0 CONTEXT KEYWORDS MATRIX                   |
|                                                                             |
|   KEYWORD          DESCRIPTION                   SAMPLE EXPRESSION          |
|   ---------------  ----------------------------  -------------------------  |
|   payload          Current message body          payload.customer.name      |
|   attributes       Inbound transport metadata    attributes.queryParams.id  |
|   vars             Developer-defined variables   vars.token                 |
|   error            Active exception details      error.description          |
|   app              Application-level metadata    app.name                   |
|   server           Host & JVM server metadata    server.dateTime            |
|   mule             Mule engine runtime metadata  mule.version               |
+-----------------------------------------------------------------------------+

A. Accessing payload

Payload data is accessed using standard object navigation, array indexing, and multi-value selectors:

%dw 2.0
output application/json
---
{
    customerName: payload.customer.name,
    primaryEmail: payload.customer.emails[0],
    allItemIds: payload.orders.*item.id
}

B. Accessing Inbound attributes

Attributes represent protocol-specific inbound metadata. Common access patterns include:

// HTTP Query Parameters: /orders?status=shipped&customer-type=gold
attributes.queryParams.status                  // Returns "shipped"
attributes.queryParams['customer-type']        // Returns "gold" (Bracket notation required!)

// HTTP URI Parameters: /customers/{customerId}/orders/{orderId}
attributes.uriParams.customerId                // Returns URI parameter
attributes.uriParams['orderId']                 // Returns URI parameter

// HTTP Headers
attributes.headers.authorization               // Returns "Bearer eyJhbGci..."
attributes.headers['content-type']             // Returns "application/json"

// HTTP Response Attributes (from HTTP Request)
attributes.statusCode                          // Returns 200, 404, 500 (Integer)
attributes.reasonPhrase                        // Returns "OK", "Not Found"

// File / SFTP Attributes
attributes.fileName                            // Returns "orders_20260822.csv"
attributes.fileSize                            // Returns 1048576 (Bytes)
attributes.path                                // Returns "/inbound/orders_20260822.csv"

[!IMPORTANT] The Bracket Notation Rule for Hyphenated Keys: If an HTTP header, query parameter, or variable name contains a hyphen (-), space, or dot (.), you must use bracket notation: attributes.headers['X-Correlation-ID']. Using dot notation without quotes (attributes.headers.X-Correlation-ID) causes DataWeave to evaluate -Correlation as a subtraction operator, resulting in a compilation or runtime error.

2. Context Objects & System Properties Reference

Beyond message data and attributes, Mule exposes system-level context objects that provide runtime, server, and environmental awareness.

A. The app Context Object

Provides metadata about the running Mule application:

  • app.name: The registered name of the Mule application (e.g., orders-system-api).
  • app.workDir: The absolute path to the application's working directory on the host file system.
  • app.encoding: The default character encoding of the application (e.g., UTF-8).
  • app.standalone: Boolean indicating whether the application is running in standalone mode.

B. The server Context Object

Provides environmental metadata about the underlying host operating system and JVM:

  • server.dateTime: The current server date and time as a timezone-aware DateTime object (|2026-08-22T13:58:45-07:00|).
  • server.nanoTime: High-resolution system time in nanoseconds, commonly used for profiling.
  • server.host: The hostname or network name of the machine hosting the runtime.
  • server.ip: The primary IP address of the host machine.
  • server.osName: Operating system name (e.g., Linux, Mac OS X, Windows 11).
  • server.osVersion: Operating system version string.
  • server.userHome: The current user home directory path.
  • server.fileSeparator: File separator character (/ on Unix, \ on Windows).

C. The mule Context Object

Provides metadata regarding the Mule runtime engine installation:

  • mule.home: The absolute path to the Mule runtime home directory.
  • mule.version: The semantic version of the Mule engine (e.g., 4.4.0, 4.5.1).
  • mule.clusterId: The cluster identifier if the server is running in a High Availability (HA) cluster.

D. Property Lookups: p('key') and Mule::p('key')

To retrieve configuration properties defined in YAML or .properties files (such as config.yaml):

// Standard property lookup
p('db.host')                                  // Returns "postgres-prod.internal"
p('api.timeout') as Number                   // Coerced to Number: 5000

// Secure property lookup (encrypted values via Secure Configuration Properties module)
Mule::p('secure::db.password')                // Decrypted password string
<!-- Logger displaying application context and audit information -->
<logger level="INFO" message="#[{
    application: app.name,
    runtimeVersion: mule.version,
    hostNode: server.host,
    executionTime: server.dateTime,
    databaseTarget: p('db.host')
}]"/>

3. Dissecting the Mule 4 Error Object

When an exception occurs during flow execution, Mule instantiates the error object. In Mule 4, error handling is structured around a rich, object-oriented error model rather than raw Java exception stack traces.

+-----------------------------------------------------------------------------+
|                        MULE 4 ERROR OBJECT STRUCTURE                        |
|                                                                             |
|   [error.description]         ---> "HTTP GET on resource failed: 404"       |
|   [error.detailedDescription] ---> "HTTP GET on 'https://api.com/users/99'  |
|                                     returned status code 404 (Not Found)"   |
|                                                                             |
|   [error.errorType]                                                         |
|   - error.errorType.namespace  ---> "HTTP"                                  |
|   - error.errorType.identifier ---> "NOT_FOUND"                             |
|   - error.errorType.asString   ---> "HTTP:NOT_FOUND"                        |
|   - error.errorType.parentErrorType ---> MULE:ANY                           |
|                                                                             |
|   [error.errorMessage]        ---> MuleMessage returned by failing endpoint |
|   - error.errorMessage.payload---> { "code": "USER_NOT_FOUND" }            |
|                                                                             |
|   [error.childErrors]         ---> Array of Error objects (Scatter-Gather)  |
+-----------------------------------------------------------------------------+

Core Properties of the error Object

Property ExpressionData TypeDescription & Example Output
error.descriptionStringConcise, human-readable summary of the error ("HTTP GET on resource failed with status code 404").
error.detailedDescriptionStringExhaustive technical diagnostics including target URLs and root causes.
error.errorType.namespaceStringThe module or component domain that raised the failure ("HTTP", "DB", "VALIDATION", "MULE").
error.errorType.identifierStringThe specific error classification ("NOT_FOUND", "CONNECTIVITY", "TIMEOUT", "UNAUTHORIZED").
error.errorType.asStringStringThe fully-qualified error type string ("HTTP:NOT_FOUND", "DB:QUERY_EXECUTION").
error.errorMessageMuleMessageThe complete MuleMessage generated by the failing connector (e.g., the JSON error payload returned by a remote REST API).
error.childErrorsArray<Error>Populated when composite routing processors fail (e.g., when multiple routes fail in <scatter-gather>, producing MULE:COMPOSITE_ROUTING).
<!-- Error Handler mapping structured error details to JSON client response -->
<error-handler>
    <on-error-continue type="HTTP:NOT_FOUND" enableNotifications="true" logException="true">
        <set-variable variableName="httpStatus" value="404"/>
        <ee:transform>
            <ee:message>
                <ee:set-payload><![CDATA[%dw 2.0
output application/json
---
{
    error: error.errorType.identifier,
    namespace: error.errorType.namespace,
    message: error.description,
    timestamp: server.dateTime,
    remoteDetails: error.errorMessage.payload default null
}]]></ee:set-payload>
            </ee:message>
        </ee:transform>
    </on-error-continue>
</error-handler>

4. Defensive DataWeave: Safe Navigation & Default Operators

In real-world integrations, incoming payloads, headers, and query parameters are frequently optional or null. Accessing a missing nested key without defensive coding causes runtime evaluation failures.

A. Safe Navigation Operator (?.)

The safe navigation operator navigates through nested objects without throwing a NullPointerException or null navigation error if an intermediate key is absent or null:

// If payload.customer is null, standard dot navigation throws an error:
// payload.customer.billingAddress.zipCode -> ERROR!

// Safe navigation returns null gracefully if any intermediate element is missing:
payload.customer?.billingAddress?.zipCode

B. Default Operator (default)

The default operator provides a fallback value if the target expression evaluates to null or is empty:

%dw 2.0
output application/json
---
{
    // Optional query parameter with fallback to page 1
    pageNumber: attributes.queryParams.page default 1 as Number,
    
    // Optional header with fallback correlation ID
    correlationId: attributes.headers['X-Correlation-ID'] default correlationId,
    
    // Safe nested navigation combined with default empty list
    orderLines: payload.order?.items default []
}

[!TIP] Defensive Coding Best Practice: Always combine safe navigation with default operators when consuming optional query parameters or headers: attributes.queryParams?.maxResults default 50.

Test Your Knowledge

An HTTP Listener receives an HTTP request containing a custom header named X-Correlation-ID. Which DataWeave expression correctly accesses the value of this header?

A
B
C
D
Test Your Knowledge

A developer needs to configure an audit logger at application startup that records the application name, the Mule runtime engine version, and the server timestamp. Which DataWeave expression correctly extracts these values?

A
B
C
D
Test Your Knowledge

A flow calls an external web service using an HTTP Request connector. When the remote service returns a 404 response, an error is caught by an On-Error Continue handler. The developer needs to log the specific error namespace and error identifier. Which DataWeave expression retrieves these two values?

A
B
C
D
Test Your Knowledge

An incoming HTTP request may or may not provide an optional query parameter named maxRecords. If the parameter is omitted by the client, the flow should assign a fallback integer value of 50. Which DataWeave expression safely achieves this without throwing an exception?

A
B
C
D