Search code examples
javaspring-mvcrest-clienthttp-request-parameters

Does springframework.web.client RestClient handles @requestParam


I try to do this:

@GetMapping("/db/video/getall")
public ResponseEntity<List<VideoDto>> getAllVideo(@RequestParam String ownerEmail) {        
        return ....;
    }
import org.springframework.web.client.RestClient;

RestClient restClient = RestClient.create("http://localhost:8095");

List<VideoDto> result = restClient.get()
    .uri("/db/video/getall")
    .accept(MediaType.APPLICATION_JSON)
    .retrieve()
    .body(new ParameterizedTypeReference<List<VideoDto>>() {});
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot</artifactId>
    <version>3.2.1</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>6.1.2</version>
  </dependency>

But I cannot find code sample showing how RestClient can pass ownerEmail as @RequestParam.

I found @PathVariable code sample insteed.

So, does RestClient handles @RequestParam ?


Solution

  • For a GET request, you can add query parameters in the URL. Spring's UriComponentsBuilder simplifies the manipulation of URIs.

    restClient.get()
        .uri(UriComponentsBuilder.fromPath("/db/video/getall")
                .queryParam("ownerEmail", "email").toUriString())
        // ...
    

    For a POST request, the body can be set to a MultiValueMap. The Content-Type can be inferred based on its contents.

    var parts = new LinkedMultiValueMap<String, Object>();
    parts.add("ownerEmail", "emailValue");
    restClient.post().uri("/db/video/getall").body(parts).retrieve().body(...);