Search code examples
javaspring-bootspring-webclient

Use Spring WebClient response in next API call?


I want to use WebClient response in the next API call. So before calling the next api some of the fields from the response extract and use them in the next api call. There is a way to block WebClient response and use it. But is there any way to do it without blocking? So my code looks like this

response = getUserByWebClient1(); // web client call 1
extract id from response
getRolesByUserId(id); // webclient call 2

Solution

  • This is not specific to WebClient, but a general concept with reactive types, here Reactor Flux and Mono.

    You can use the flatMap operator to achieve just that.

    // given UserService with a method "Mono<User> getCurrentUser()"
    // and RolesService with a method "Mono<RoleDetails> getRolesForUser(Long userId)"
    
    Mono<RolesDetails> roles = userService.getCurrentUser()
        .flatMap(user -> rolesService.getRolesForUser(user.getId());