Spring boot GraphQL Client

Spring boot GraphQL Client

In this article, we'll learn about the spring boot GraphQL client. With the help of the GraphQL client, we can retrieve data from the GraphQL server.

In the Last Article we have learned about the basics of GraphQL and created a GraphQL server, here as part of the demo, we'll try to connect that server with the help of the GraphQL client. As we'll retrieving data from GraphQL-based API, we need to specify a list of the attributes we required as part of the query.

I have added a core code snippet as part of the demo, for full code reference refer to GITHUB

Prerequisites

  • JDK 17+
  • Maven
  • Basic knowledge of Java, Spring boot

GraphQL Client

  • Create a spring boot web application. Add GraphQL and webflux dependency

          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-graphql</artifactId>
          </dependency>
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-webflux</artifactId>
          </dependency>
    
  • As part of the demo, we'll connect to GraphQL server with the help of HTTP, so create HttpGraphQlClient object and specify base URL.

          @Bean
            HttpGraphQlClient httpGraphQlClient(){
                return HttpGraphQlClient.builder().url("http://localhost:8080/graphql").build();
            }
    
  • Add the below code on CommandLineRunner so it can run on application startup. With the help of HttpGraphQlClient we can make any query to the GraphQL server. Here we will use the department list query that we have used in the last demo. If we want to retrieve any other type of data, then we just need to change the query only no need to change the base URL.

    @Bean
      public CommandLineRunner CommandLineRunnerBean(HttpGraphQlClient httpGraphQlClient) {
          return (args) -> {
              String query = """
                          query {
                             departments {
                               id
                               name
                               employees {
                                 id
                                 name
                               }
                             }
                           }
                      """;
    
              List<Department> departmentList =  httpGraphQlClient.document(query).retrieve("departments").toEntityList(Department.class).block();
              System.out.println("department List " + departmentList);
          };
      }
    

    Test

  • It will display the below output on application startup.
  • Screenshot 2022-06-18 223332.png