It took me forever to figure out this seemingly simple task so now I want to share in case another mule developer out there is having the same problem and can stumble across this example!
Here’s an example DataWeave 2.0 function that captures the HTTP status code and reason phrase from an HTTP response:
extractHttpStatus(response: HttpResponse): String =
response.statusCode ++ " " ++ response.reasonPhrase
This function takes an HttpResponse
object as input and returns a string that contains both the status code and reason phrase, separated by a space.
You can use this function in your DataWeave script to extract the HTTP status code and reason phrase from an HTTP response. For example, if you’re using the http
connector to make an HTTP request, you can call this function to extract the status code and reason phrase like this:
%dw 2.0
import * from dw::module::HTTP
output application/json
---
{
responseStatus: extractHttpStatus(http("https://example.com").get())
}
In this example, we’re making a GET request to https://example.com
using the http
connector, and then passing the resulting HttpResponse
object to the extractHttpStatus
function to extract the status code and reason phrase. The resulting JSON output will contain a responseStatus
field that contains the status code and reason phrase as a string, like this:
{
"responseStatus": "200 OK"
}
Also ..if you just want to cherry pick the reason phrase from a payload returned …
%dw 2.0
import * from dw::module::HTTP
input payload application/json output application/json
—
{ responseReasonPhrase: http.headers(payload)[“reason-phrase”] }