0

I want to pass the generic request body while making API call through WebClient. I have dynamic key-value pairs in the database like (key1-value1, key2-value2, key3-value3). This key-value may grow or shrink.

Is there any way to call API with dynamic data with the JSON request body?

webClient.post().uri(uri).header(CONTENT_TYPE, APPLICATION_JSON)
            .body({DYANAMIC JSON}).retrieve().onStatus(HttpStatus::isError, clientResponse -> {
                return Mono.error(new Exception("error"));
            }).bodyToMono(String.class);

Thank you

salman irfan khandu
  • 109
  • 1
  • 3
  • 12

2 Answers2

3

You can just pass the body as map and in body you can map it to either Map.class or Object class. Based on your requirement you can pass JsonObject as well.

Map<String, String> r = new HashMap<>();
    webClient.post().uri(uri).header(CONTENT_TYPE, APPLICATION_JSON)
                    .body(Mono.just(r), Map.class).retrieve().onStatus(HttpStatus::isError, clientResponse -> {
                        return Mono.error(new Exception("error"));
                    }).bodyToMono(String.class);
3

If you already have the full request body, you can use the shortcut method bodyValue.

Object requestBody = ...;
webClient.post()
    .uri(uri)
    .contentType(MediaType.APPLICATION_JSON)
    .bodyValue(requestBody)
    .retrieve()
    .onStatus(HttpStatus::isError, clientResponse -> {
        return Mono.error(new Exception("error"));
    })
    .bodyToMono(String.class);

Inserting a request body is described in the docs here: https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-client-body

Note: You can also use the shortcut contentType(MediaType.APPLICATION_JSON) instead of header("Content-Type", MediaType.APPLICATION_JSON)

Michael R
  • 1,753
  • 20
  • 18
  • He literally said he wants a dynamic request body, NOT a premade object. – Krusty the Clown Sep 16 '22 at 03:16
  • `requestBody` here is any object that serializes to JSON. This example does not require or imply that `requestBody` is static. It just needs to exist prior to calling `webClient.post()`. The author did not clarify what type was being used for "{DYNAMIC JSON}". It could be a string, a map, whatever. – Michael R Sep 17 '22 at 19:09