How to pass path variable by names in web client in Spring boot?
Asked Answered
S

3

7

I want to pass path variable using name in web client. I could pass query param by key value pair but how to pass path variable.

For query param, we can do like this by passing key value pair

 this.webClient.get()
  .uri(uriBuilder - > uriBuilder
    .path("/products/")
    .queryParam("name", "AndroidPhone")
    .queryParam("color", "black")
    .queryParam("deliveryDate", "13/04/2019")
    .build())
  .retrieve();

For path variable, we can do like this by passing value

this.webClient.get()
  .uri(uriBuilder - > uriBuilder
    .path("/products/{id}/attributes/{attributeId}")
    .build(2, 13))
  .retrieve();

I want like below

this.webClient.get()
  .uri(uriBuilder - > uriBuilder
    .path("/products/{id}/attributes/{attributeId}/")
    .pathParam("attributeId", "AIPP-126")
    .pathParam("id", "5254136")
    .build())
  .retrieve();
Stereoscope answered 16/6, 2020 at 6:57 Comment(0)
A
10

In addition to @boobalan's anwser, the simplest way for the case mentioned is:

   webClient.get()
    .uri("/products/{id}/attributes/{attributeId}", 2, 13)
    .retrieve();
Ancipital answered 16/6, 2020 at 8:7 Comment(0)
P
1

It is a design decision.

Why such a construct a there for queryParam but not for pathParam?

In the case of query param, the order in which any query param is present in the uri doesn't matter and the declaration(and assignment of value) of .queryParam("name", "AndroidPhone") just once in the URIBuilder is enough.

Whereas, in the case of path param, the order in which any or different path params appear in the uri matters:

Your suggestion forces declaration of any pathParam like attributeId in the exact relative position in the URI once and the assignment of the value for that attributeId separately, which requires the user to present the correct text attributeId input twice in total.

Instead of all this, the URIBuilder has construct only to declare all the path params only once while declaring and pass all their values using .build(..) in the sequential order.

Piecemeal answered 16/6, 2020 at 7:28 Comment(1)
Can't you show what you're saying with some code ?Bivins
S
1

Thanks @boobalan @puce. I agree with design decision. But my goal is pass path params by name. I could pass both path/query params once and it works.

String url = "http://localhost:8000/{id}/{name}/{id}/{name}?param1={id}&param2={cost}";
        Map<String, String> params = new HashMap<>();
        params.put("id", "123");
        params.put("name","Prabhu");
        params.put("cost","35.26");

        WebClient.create().method(HttpMethod.GET)
        .uri(url, params).retrieve();

The final url is http://localhost:8000/123/Prabhu/123/Prabhu?param1=123&param2=35.26

Stereoscope answered 17/6, 2020 at 8:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.