6.2 HTTP Request Connector: Headers, Query Params, Response Timeouts & Target Variables

Key Takeaways

  • The HTTP Request Connector (<http:request>) acts as an outbound HTTP client configured via a global <http:request-config> defining host, port, base path, TLS context, connection pooling, and response timeouts.
  • Outbound headers, query parameters, and URI parameters are configured using nested DataWeave maps (<http:headers>, <http:query-params>, <http:uri-params>), cleanly separating dynamic query logic from static URL strings.
  • By default, an HTTP Request replaces both the current message payload and attributes with the HTTP response body and response attributes (attributes.statusCode, attributes.headers); utilizing the target attribute (e.g., target="vars.accountData") preserves the original payload.
  • The responseTimeout attribute determines the maximum duration (in milliseconds) the connector waits for an HTTP response before aborting and throwing an HTTP:TIMEOUT error.
  • When an external HTTP service returns a non-successful status code (4xx/5xx), the connector throws specific error types (e.g., HTTP:NOT_FOUND, HTTP:UNAUTHORIZED, HTTP:BAD_REQUEST), and the remote error response body is preserved inside error.errorMessage.payload.
Last updated: August 2026

HTTP Request Connector: Headers, Query Params, Response Timeouts & Target Variables

In modern API-led connectivity, Mule applications constantly consume downstream RESTful web services, SaaS endpoints, microservices, and internal System APIs. The HTTP Request Connector (<http:request>) is the foundational component for executing outbound HTTP/HTTPS calls in Mule 4. Mastering its configuration—specifically parameter mapping, payload preservation using target variables, status code validation, and error management—is a core requirement of the Salesforce Certified MuleSoft Developer I exam.


1. Global HTTP Request Configuration (<http:request-config>)

An <http:request-config> defines shared connection parameters, base URLs, security contexts, and default timeouts for one or more outbound request operations across the Mule application.

<http:request-config name="Customer_API_Request_Config" doc:name="HTTP Request configuration" basePath="/api/v1">
    <http:request-connection 
        host="${customer.api.host}" 
        port="${customer.api.port}" 
        connectionIdleTimeout="30000"
        usePersistentConnections="true">
        <tls:context>
            <tls:trust-store path="truststore.p12" password="${secure::truststore.pwd}" type="pkcs12" />
        </tls:context>
    </http:request-connection>
</http:request-config>

Core Global Configuration Properties:

  • host & port: The target server hostname (or IP) and port number (e.g., api.example.com, port 443 for HTTPS or 80 for HTTP).
  • basePath: The root URL prefix for all requests using this configuration (e.g., /api/v1). Individual operations append their specific relative path (e.g., /customers/{id}).
  • connectionIdleTimeout: Maximum time (in milliseconds) an idle TCP connection remains open in the connection pool before being closed.
  • usePersistentConnections: Enables HTTP 1.1 keep-alive TCP connection pooling (default: true), reducing handshake latency across repeated calls.
  • responseTimeout: Global default duration to wait for an HTTP response before throwing HTTP:TIMEOUT (default: 10,000 ms).

2. Dynamic Outbound Parameters: Query, Header & URI Parameters

When invoking an endpoint, requests often require dynamic URI parameters, query parameters, and custom HTTP headers. Mule 4 provides dedicated XML child elements evaluated as DataWeave expressions:

+-----------------------------------------------------------------------------------------+
|                           OUTBOUND HTTP REQUEST STRUCTURE                               |
|                                                                                         |
|   URL: https://api.enterprise.com:443/api/v1/customers/{customerId}/orders?status=OPEN |
|                                                                                         |
|   1. BASE PATH & HOST   ---> Defined in <http:request-config>:                          |
|                              host="api.enterprise.com", basePath="/api/v1"              |
|                                                                                         |
|   2. OPERATION PATH     ---> path="/customers/{customerId}/orders"                      |
|                                                                                         |
|   3. URI PARAMS         ---> <http:uri-params> #[{'customerId': vars.targetCustId}]    |
|                                                                                         |
|   4. QUERY PARAMS       ---> <http:query-params> #[{'status': 'OPEN', 'limit': 25}]    |
|                                                                                         |
|   5. HEADERS            ---> <http:headers> #[{                                         |
|                                'Authorization': 'Bearer ' ++ vars.token,                |
|                                'X-Correlation-ID': correlationId                        |
|                              }]                                                         |
|                                                                                         |
|   6. BODY / PAYLOAD     ---> #[payload] (or custom DataWeave transformation)            |
+-----------------------------------------------------------------------------------------+

Comprehensive Inbound-to-Outbound Request Example:

<http:request 
    method="POST" 
    config-ref="Customer_API_Request_Config" 
    path="/customers/{customerId}/transactions" 
    doc:name="Post Customer Transaction" 
    responseTimeout="15000">
    
    <!-- 1. Outbound Body (Defaults to current payload if omitted) -->
    <http:body><![CDATA[#[
        {
            amount: vars.orderAmount,
            currency: "USD",
            paymentMethod: payload.paymentType
        }
    ]]]></http:body>
    
    <!-- 2. URI Parameters (Replaces {customerId} placeholder in path) -->
    <http:uri-params><![CDATA[#[
        {
            customerId: vars.customerId
        }
    ]]]></http:uri-params>
    
    <!-- 3. Query Parameters (Appended to URL as ?notify=true&channel=MOBILE) -->
    <http:query-params><![CDATA[#[
        {
            notify: true,
            channel: attributes.queryParams.channel default "WEB"
        }
    ]]]></http:query-params>
    
    <!-- 4. HTTP Headers -->
    <http:headers><![CDATA[#[
        {
            "Content-Type": "application/json",
            "Authorization": "Bearer " ++ vars.jwtToken,
            "X-Client-ID": p('client.id'),
            "X-Correlation-ID": correlationId
        }
    ]]]></http:headers>
</http:request>

[!TIP] URI Parameter Placeholder Matching The keys declared in <http:uri-params> must exact match the placeholder names enclosed in curly braces {paramName} in the path attribute. For example, path="/orders/{orderId}" requires <http:uri-params>#[{'orderId': vars.orderId}].


3. The Target Variable Pattern (target & targetValue)

One of the most critical concepts on the MuleSoft Developer I certification is understanding how HTTP Request execution affects the Mule Event.

Default Behavior (Overwriting Payload & Attributes)

By default, when an <http:request> executes successfully:

  1. The original payload is completely overwritten by the HTTP response body returned from the downstream server.
  2. The original attributes (e.g., inbound HTTP Listener headers, query params) are completely overwritten by the downstream HTTP response attributes (attributes.statusCode, attributes.headers, attributes.reasonPhrase).
  3. Flow variables (vars) remain intact.
DEFAULT BEHAVIOR:
[Inbound Order Payload] ---> [<http:request> (Lookup Customer)] ---> [Customer Response Payload]
* Original Order Payload is LOST unless manually saved to a variable prior to the request.

The Target Pattern (Preserving Payload)

To preserve the existing payload while enriching the flow with downstream data, configure the target parameter (and optional targetValue):

<http:request 
    method="GET" 
    config-ref="Customer_API_Request_Config" 
    path="/customers/{customerId}" 
    target="vars.customerData" 
    targetValue="#[payload]" 
    doc:name="Get Customer Profile">
    <http:uri-params><![CDATA[#[{'customerId': payload.customerId}]]]></http:uri-params>
</http:request>
TARGET VARIABLE BEHAVIOR:
[Inbound Order Payload] ---> [<http:request> target="vars.customerData"] ---> [Inbound Order Payload]
                                                                           + vars.customerData = [Customer Info]
* Original Order Payload remains intact in payload; downstream response is saved to vars.customerData.

Target Configuration Options:

  • target="vars.customerData": Stores the entire response body into vars.customerData. payload and attributes remain unchanged.
  • target="vars.creditRating" targetValue="#[payload.score]": Evaluates a DataWeave expression against the response and stores only the specific sub-field (score) into vars.creditRating.
  • target="vars.serviceResponse" targetValue="#[{'body': payload, 'statusCode': attributes.statusCode}]": Captures both the response body and the HTTP response status code into a custom object without altering the main flow payload.

4. Response Validation & Status Code Mapping

By default, the HTTP Request Connector validates HTTP responses against the standard HTTP status range 200..599.

+-----------------------------------------------------------------------------------------+
|                         HTTP REQUEST STATUS CODE HANDLING                               |
|                                                                                         |
|   Status 200-399  ---> Success: Normal flow continuation                                |
|                                                                                         |
|   Status 400      ---> Throws Error: HTTP:BAD_REQUEST                                   |
|   Status 401      ---> Throws Error: HTTP:UNAUTHORIZED                                  |
|   Status 403      ---> Throws Error: HTTP:FORBIDDEN                                     |
|   Status 404      ---> Throws Error: HTTP:NOT_FOUND                                     |
|   Status 405      ---> Throws Error: HTTP:METHOD_NOT_ALLOWED                            |
|   Status 415      ---> Throws Error: HTTP:UNSUPPORTED_MEDIA_TYPE                        |
|   Status 500      ---> Throws Error: HTTP:INTERNAL_SERVER_ERROR                         |
|   Status 503      ---> Throws Error: HTTP:SERVICE_UNAVAILABLE                           |
|   Other 4xx/5xx   ---> Throws Error: HTTP:STATUS_CODE_ERROR (e.g. 422, 502, 504)        |
+-----------------------------------------------------------------------------------------+

Customizing Response Validators

If an API returns business payloads with 4xx status codes that you wish to process as valid responses without raising errors, you can customize the <http:response-validator>:

<http:request method="GET" config-ref="Customer_API_Request_Config" path="/lookup" doc:name="Lookup">
    <http:response-validator>
        <!-- Treat 200 through 404 as non-error responses -->
        <http:success-status-code-validator values="200..404" />
    </http:response-validator>
</http:request>

5. Timeouts, Connectivity & Error Handling

When an outbound HTTP request fails, Mule raises an error belonging to the HTTP namespace:

Error TypeDescription & Typical Trigger
HTTP:CONNECTIVITYFailed to establish TCP connection (DNS resolution failure, target server down, firewall blocking port).
HTTP:TIMEOUTConnection established, but target server took longer than responseTimeout to return the complete response.
HTTP:SECURITYTLS/SSL handshake failure, untrusted SSL certificate, expired certificate.
HTTP:BAD_REQUESTRemote server returned HTTP status 400.
HTTP:UNAUTHORIZEDRemote server returned HTTP status 401 (invalid/expired credentials or token).
HTTP:FORBIDDENRemote server returned HTTP status 403 (insufficient privileges).
HTTP:NOT_FOUNDRemote server returned HTTP status 404 (resource does not exist).
HTTP:INTERNAL_SERVER_ERRORRemote server crashed or encountered an unhandled exception returning HTTP status 500.
HTTP:STATUS_CODE_ERRORGeneral fallback error type for any 4xx/5xx status code without a dedicated error type.

Accessing the Downstream Error Response Body

When a downstream service returns a 4xx or 5xx error containing a diagnostic JSON/XML payload (such as error details with error code and description), this error body is not stored in payload. It is stored inside the error.errorMessage.payload object:

<error-handler>
    <on-error-continue type="HTTP:BAD_REQUEST, HTTP:NOT_FOUND" doc:name="Handle Client Errors">
        <logger level="WARN" message="#['Downstream API returned error: ' ++ write(error.errorMessage.payload, 'application/json')]" />
        <set-payload value="#[error.errorMessage.payload]" doc:name="Pass Error to Caller" />
        <set-variable variableName="httpStatus" value="#[error.errorMessage.attributes.statusCode default 400]" doc:name="Set Status" />
    </on-error-continue>
</error-handler>

[!IMPORTANT] error.description vs error.errorMessage.payload

  • error.description: Contains Mule runtime's standard English error summary (e.g., "HTTP GET on resource 'http://api.example.com/customers/99' failed: not found (404).").
  • error.errorMessage.payload: Contains the actual response payload (JSON/XML/text) returned by the target HTTP server during the failure.

6. Exam Watch: Core HTTP Request Scenarios

[!IMPORTANT] Target Variable Preserves Message Payload When an exam question asks how to call an external service for lookup data without losing the current message payload, the solution is always setting the target attribute on the <http:request> component (e.g., target="vars.lookupData").

[!WARNING] Attributes are Replaced by Default If target is NOT used, the outbound HTTP call replaces attributes with the HTTP response attributes. Any original inbound HTTP Listener query parameters (attributes.queryParams) or URI parameters are lost.

[!TIP] Response Timeout Units The responseTimeout attribute on <http:request> and <http:request-config> is always specified in milliseconds (e.g., 30000 = 30 seconds).

Test Your Knowledge

A Mule flow receives an inbound JSON purchase order via an HTTP Listener. The flow must invoke an external Credit Verification System API via an HTTP Request Connector to validate the customer's credit score without losing or overwriting the original purchase order payload. How should the HTTP Request Connector be configured?

A
B
C
D
Test Your Knowledge

A developer needs to configure an HTTP Request Connector to call an endpoint defined as GET https://inventory.internal.net:8443/warehouse/v2/items/{sku}/availability?location=US-EAST. The global configuration sets host="inventory.internal.net", port="8443", and basePath="/warehouse/v2". How should the HTTP Request operation be configured?

A
B
D
Test Your Knowledge

A downstream payment processing API experiences a network partition and takes 45 seconds to respond. The calling Mule application has an HTTP Request operation configured with responseTimeout="10000" (10 seconds). What occurs when 10 seconds elapse without a response?

A
B
C
D
Test Your Knowledge

An HTTP Request operation calls a remote partner service that responds with HTTP status 400 Bad Request and a JSON body containing an error code and description. Inside the flow's On-Error Propagate handler, how can the developer access this JSON error body returned by the remote partner?

A
B
C
D