Monday, October 6, 2025

Reactive Java with Spring WebFlux and Reactor

Utilizing the reactive HTTP shopper

Now, let’s make an endpoint that accepts an ID parameter. We’ll use the Spring reactive HTTP shopper and An API of Ice and Fireplace to make a request for a Recreation of Thrones character based mostly on ID. Then, we’ll ship the character knowledge again to the consumer. Discover the brand new apiChain() technique and its imports right here:


import org.springframework.internet.reactive.operate.shopper.WebClient;

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

In the event you navigate to localhost:8080/character/148, you’ll get the biographical data for who is clearly the most effective character in The Recreation of Thrones.

This instance works by accepting the ID path parameter and utilizing it to make a request to the WebClient class. On this case, we’re creating an occasion for our request, however you’ll be able to create a WebClient with a base URL after which reuse it repeatedly with many paths. We put the ID into the trail after which name retrieve adopted by bodyToMono(), which transforms the response right into a Mono. Keep in mind that all this stays nonblocking and asynchronous, so the code that waits for the response from the API won’t block the thread. Lastly, we use map() to formulate a response again to the consumer.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles

PHP Code Snippets Powered By : XYZScripts.com