In this article, I will explain how to pass non-mandatory query parameters using an HTTP Request connector in Mule 4.
The HTTP Request Connector provides the most common way to consume an external HTTP service. When sending HTTP requests you can choose what method to use (GET, POST, etc) and it may include a body, headers, attachments, query parameters, URI parameters and form parameters.
The most common use of HTTP Query parameters is to send them with HTTP Request and get data based on those parameters.
In Mule 4 in the Request section of the HTTP request connector under the Query Parameters tab, we can specify the name and the value for the query parameters that we are going to send (Refer to Figure 1).
What happens if param1 is mandatory, butÂ param2 and param3 are optional?
For example, we can use postman to make HTTP Call with only the mandatory parameter (param1) and donâ€™t send the optional parameters.
In that case, the URL will look like the example below:
The problem we are trying to solve appears when the value of the Query parameter is null and we end up by not passing the value for that parameter. The URL that we are sending to the provider will look like the example below:
In this scenario, the response that we are going to receive will be unexpected because the values for param2 and param3 are null but our provider expects some values for those parameters. What we are trying to achieve is that in case there are no values for the optional parameters, they should be excluded from the HTTP request.
The solution for this problem is to add conditions for all optional parameters and in our case, we are going to use If state without else statement conditions.
We can achieve that by switching from literal mod to expression mod (Refer to Figure 2):
The next step is to set if conditions for the optional parameters (param2 and param3) like in the code snippet from below:
This solution can be also used to set optional URI and Header parameters.