Reactive Java with Spring WebFlux and Reactor

Using the reactive HTTP client

Now, let’s make an endpoint that accepts an ID parameter. We’ll use the Spring reactive HTTP client and An API of Ice and Fire to make a request for a Game of Thrones character based on ID. Then, we’ll send the character data back to the user. Notice the new apiChain() method and its imports here:


import org.springframework.web.reactive.function.client.WebClient;

@GetMapping("character/{id}")
  public Mono getCharacterData(@PathVariable String id) {
    WebClient client = WebClient.create("https://anapioficeandfire.com/api/characters/");
    return client.get()
      .uri("/{id}", id)
      .retrieve()
      .bodyToMono(String.class)
      .map(response -> "Character data: " + response);
  }

If you navigate to localhost:8080/character/148, you’ll get the biographical information for who is obviously the best character in The Game of Thrones.

This example works by accepting the ID path parameter and using it to make a request to the WebClient class. In this case, we are creating an instance for our request, but you can create a WebClient with a base URL and then reuse it repeatedly with many paths. We put the ID into the path and then call retrieve followed by bodyToMono(), which transforms the response into a Mono. Remember that all this remains nonblocking and asynchronous, so the code that waits for the response from the API will not block the thread. Finally, we use map() to formulate a response back to the user.

Donner Music, make your music with gear
Multi-Function Air Blower: Blowing, suction, extraction, and even inflation

Leave a reply

Please enter your comment!
Please enter your name here