How to set up optional query parameters in HTTP Request connector (Mule 4)?

23 Sep, 2019 | 2 minutes read

In this article, I will explain how to pass query parameters in HTTP request 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 in Mule 4, 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 in Mule 4 under the Query Parameters tab, we can specify the name and the value for the Mulesoft query parameters that we are going to send (Refer to Figure 1).

Figure 1: Set query parameters
(Figure 1 – Set Mule 4 query parameters)

What happens if param1 is mandatory, but param2 and param3 are an optional query parameter?
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:
http://localhost:8081/api?param1=value1

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:

http://localhost:8082/request?param1=value1&param2=null&param3=null

In this scenario about query parameters in Mule 4, 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):

Figure 2: Switch to expression mode
(Figure 2 – Switch to expression mode)

The next step is to set if conditions for the optional parameters (param2 and param3) like in the code snippet from below:

As a Senior PHP Programmer, you can also use this solution to set optional URI and Header parameters.

Now you know the process of making HTTP request query parameters in Mule 4!