Skip to content
Advertisement

How can I receive dynamically number of query params in Rest Client – Quarkus?

I need create a rest client to access a URI that can receive 0 or n query params.

Example:

https://xpto?page=0&size=10&brand=abc&color=blue or
https://xpto?page=0&size=10&brand=abc or
https://xpto?page=0&size=10 or
https://xpto

how could i do this here?

@RegisterRestClient
  public interface BarService {
  @GET
  @Path("/xpto")
  Response get(@QueryParam ...);
}

Advertisement

Answer

Please refer to How to send a query params map using RESTEasy proxy client, similar issue is being discussed.

You can define your client similar to below:

@RegisterRestClient
  public interface BarService {
  @GET
  @Path("/xpto")
  Response get(Map<String, String> queryParamMap);
}

And you can define ClientRequestFilter for converting the Map to Query Parameters:

import java.io.IOException;
import java.util.Map;

import javax.ws.rs.HttpMethod;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.ext.Provider;

@Provider
public class QueryParamBuildingFilter implements ClientRequestFilter {

    @Override
    public void filter(ClientRequestContext requestContext) throws IOException {
        if (requestContext.getEntity() instanceof Map && requestContext.getMethod().equals(HttpMethod.GET)) {
            UriBuilder uriBuilder = UriBuilder.fromUri(requestContext.getUri());
            Map allParam = (Map)requestContext.getEntity();
            for (Object key : allParam.keySet()) {
                uriBuilder.queryParam(key.toString(), allParam.get(key));
            }
            requestContext.setUri(uriBuilder.build());
            requestContext.setEntity(null);
        }
    }

}
Advertisement