← All articles
Mule 4.x · MuleSoft

Mule 4 - Add Custom Response Headers

Migrating an application from Mule 3.x to Mule 4.x changes several implementation details, including how outbound HTTP response metadata is handled. One practical requirement is returning custom response headers from selected APIs.

Use case

Suppose an API needs to return an x-warning response header so consumers can identify that an endpoint is deprecated. In Mule 3.x, this type of behavior could be implemented with set-property, but Mule 4 requires a different approach.

The following reusable flow prepares the custom response header and can be referenced from APIs that need the warning:

<flow name="addDeprecatedWarningHeader">
  <scripting:execute engine="groovy">
    <scripting:code>
      vars.outboundHeaders.put('x-warning', 'Deprecated API');
      return payload;
    </scripting:code>
  </scripting:execute>
</flow>
View original Gist ↗

The HTTP Listener can then include the resulting value in the response headers:

<http:listener config-ref="api-httpListenerConfig" path="/api/*">
  <http:response statusCode="#[vars.httpStatus default 200]">
    <http:headers>#[vars.outboundHeaders default {}]</http:headers>
  </http:response>
  <http:error-response statusCode="#[vars.httpStatus default 500]">
    <http:body><![CDATA[#[payload]]]></http:body>
    <http:headers>#[vars.outboundHeaders default {}]</http:headers>
  </http:error-response>
</http:listener>
View original Gist ↗

Takeaway

Although this example uses an x-warning header for API deprecation, the same pattern can be used to return one or more custom response headers based on application-specific requirements.