4

I am looking for a solution to implement an GraphQL api call from spring-boot application, having query schema as follows:

query {
    getDetailsByRefNumber(RefNumbers: "")
    {
        field1,
        field2,
        field3 
    } 
}

Does anyone have any idea how to implement this ? Gone through one of the below links, but didn't find any solution

Are there any Java based Graphql client to invoke graphql server from java code?

Stan Ostrovskii
  • 528
  • 5
  • 19
m23
  • 61
  • 1
  • 2
  • 6

1 Answers1

8

You can use "graphql-webclient-spring-boot-starter" library that is available at:

https://github.com/graphql-java-kickstart/graphql-spring-webclient

<!-- https://mvnrepository.com/artifact/com.graphql-java-kickstart/graphql-webclient-spring-boot-starter -->
<dependency>
  <groupId>com.graphql-java-kickstart</groupId>
  <artifactId>graphql-webclient-spring-boot-starter</artifactId>
  <version>1.0.0</version>
</dependency>

A sample implementation can be something like this:

Assuming that you have MyEntity object:

public class MyEntity
{
    String field1;
    String field2;
    String field3;
    //getter and setters here
}

Also you have two graphql query files under "src/main/resources" folder:

query1.graphql:

#query1.graphql
#this query returns a list of some_detail_entity
query getDetailListByRefNumber($RefNumber: String!){
    some_detail_entity(where: {RefNumber : { _eq: $RefNumber } }) {
        field1
        field2
        field3 
    } 
}

query2.graphql:

#query2.graphql
#this query returns a single some_detail_entity
query getDetailByRefNumber($RefNumber: String!){
    some_detail_entity_by_pk(RefNumber : $RefNumber) {
        field1
        field2
        field3 
    } 
}

You can use this snippet to call graphql server to query & fetch some data:

ObjectMapper objectMapper = new ObjectMapper();

WebClient webClient = WebClient.builder()
.baseUrl("https://endpoint-url-of-graphql.com")//url of graphql instance
.defaultHeader("auth-token", "some-cryptic-code-if-required")//if auth header not required, just delete this line
.build();

GraphQLWebClient graphqlClient = GraphQLWebClient.newInstance(webClient, objectMapper);

//if expecting a single entity (not array)
MyObject entity = graphqlClient.post("query2.graphql", 
Map.of("RefNumber", "A7EED900-9BB4-486F-9F7C-2136E61E2278"), MyEntity.class)
            .block();   

            
//if expecting a list of entity (array)
var response = graphqlClient.post(GraphQLRequest.builder().resource("query1.graphql")
        .variables(Map.of("RefNumber", "A7EED900-9BB4-486F-9F7C-2136E61E2278")).build())
                .block();   

List<MyEntity> entityList = response.getFirstList(MyEntity.class);
Murat
  • 370
  • 4
  • 3