Jerome VDL
Jerome VDL

Reputation: 3526

Spring Boot Feign requestParam containing an array

I'm trying to query the https://transport.opendata.ch/ API. In this API, it is possible to filter the response to avoid a big payload (using ?fields[]=...).

For example : http://transport.opendata.ch/v1/connections?from=Lausanne&to=Zurich&fields[]=connections/from&fields[]=connections/to

I'm using Spring Boot and Feign, here is my code :

@FeignClient(value = "transport", url = "${transport.url}")
public interface TransportClient {

    @RequestMapping(method = GET, value = "/connections", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    Connections getConnections(@RequestParam("from") String from, @RequestParam("to") String to, @RequestParam("fields[]") String[] fields);

    default Connections getConnections(String from, String to) {
        return getConnections(from, to, new String[] {"connections/from", "connections/to"});
    }
}

The trouble is the generated request :

http://transport.opendata.ch/v1/connections?from=Lausanne&to=Zurich&fields%5B%5D=connections%2Ffrom%2Cconnections%2Fto

As you can see, the url is encoded and the array is not correctly binded (using comma instead of several fields in the url).

Is there any way to achieve this? If it cannot be done with FeignClient (Spring), maybe with Feign it is possible ?

Thanks for your help.

Upvotes: 1

Views: 4690

Answers (2)

Mạnh Quyết Nguyễn
Mạnh Quyết Nguyễn

Reputation: 18235

Your typical request looks like:

 /api?fields=1&fields=2&fields=3

or

 /api?fields=1,2,3

And the controller method is:

@RequestMapping(method = GET, value = "/api", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
Connections getConnections(@RequestParam("fields") List<String> fields)

Upvotes: 2

Jerome VDL
Jerome VDL

Reputation: 3526

I've just found a solution:

@FeignClient(value = "transport", url = "${transport.url}")
public interface TransportClient {

    @RequestMapping(method = GET, value = "/connections?fields[]=connections/from&fields[]=connections/to", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    Connections getConnections(@RequestParam("from") String from, @RequestParam("to") String to);
}

I'm lucky because my fields are static, so I could put them directly in the URI, but how to handle this properly in a generic way?

Upvotes: 0

Related Questions