GraphQL in Java

This page gives you a step-by-step overview on how to get started with GraphQL in Java.

1. Dependencies

To get started, you just need a current LeanIX Pathfinder Java SDK. With Maven, it includes all other dependencies, e.g. a JSON library:

<dependency>
    <groupId>net.leanix</groupId>
    <artifactId>leanix-sdk-java</artifactId>
    <version>3.9.7</version>
</dependency>

2. Create a query and a mutation class

As illustrated in Understand GraphQL in 10 minutes, there are two main concepts in GraphQL: A query and a mutation. We will create a Java class for each, which then can be expanded to a library for more calls.

Both query and mutation rely on a common base class which brings the logic to execute the call:

package net.leanix.graphql;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import net.leanix.api.GraphqlApi;
import net.leanix.api.common.ApiClient;
import net.leanix.api.common.ApiException;
import net.leanix.api.models.GraphQLRequest;
import net.leanix.api.models.GraphQLResult;

public abstract class GraphQLQuery {
    
    private static final ObjectMapper mapper;
    static {
        mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);
    }

    public static JsonNode executeQuery(ApiClient client, GraphQLQuery query) throws ApiException {
        GraphQLRequest gqlRequest = new GraphQLRequest();
        gqlRequest.setQuery(query.build());
        GraphQLResult res = new GraphqlApi(client).processGraphQL(gqlRequest);

        if (res.getErrors() != null) {
            throw new ApiException(res.getErrors().toString());
        }
        return mapper.valueToTree(res.getData());
    }

    public JsonNode execute(ApiClient client) throws ApiException {
        return GraphQLQuery.executeQuery(client, this);
    }

    public abstract String build();
}

The "GetFactSheetById" class accepts a return string, so you can accurately choose which attributes or relations to return.

package net.leanix.graphql;

public class GetFactSheetById extends GraphQLQuery {

    private String id;
    private String returns;

    public GetFactSheetById(String id) {
        this.id = id;
        this.returns = "id rev displayName name type";
    }

    public GetFactSheetById(String id, String returns) {
        this.id = id;
        this.returns = returns;
    }

    public String build() {
        return "{ factSheet(id: \"" + id + "\") { " + returns + " } }";
    }

}

The "UpdateFactSheet" class takes a map of arguments as input, which are then compiled into patches.

package net.leanix.graphql;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class UpdateFactSheet extends GraphQLQuery {

    private String id;
    private Map<String, String> values = new HashMap<>();
   
    public UpdateFactSheet(String id, Map<String, String> values) {
        this.id = id;
        this.values = values;
    }

    public String build() {
        String args = "id: \"" + id + "\", patches: [";

        List<String> ops = new ArrayList<String>();
        for (Entry<String, String> entry : values.entrySet()) {
            ops.add("{op: replace, path: \"" + entry.getKey() + "\", value: \"" + entry.getValue() + "\"}");
        }
        args += String.join(",", ops);
        
        args += "]";

        return mutation("updateFactSheet", args, "factSheet { id rev displayName }");
    }
  
    private String mutation(String type, String args, String returns) {
        return "mutation { " + type + "(" + args + ") { " + returns + " } }";
    }

}

3. Putting it all together

The following snippet shows how to initialize the ApiClient with the correct parameter, and then how to get and update a Fact Sheet.

package net.leanix;

import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.databind.JsonNode;

import net.leanix.api.common.ApiClient;
import net.leanix.api.common.ApiClientBuilder;
import net.leanix.api.common.ApiException;
import net.leanix.graphql.GetFactSheetById;
import net.leanix.graphql.UpdateFactSheet;

public class GraphQLExample {

    public static void main(String[] args) throws ApiException {
        ApiClient apiClient = new ApiClientBuilder()
          .withBasePath("https://<domain>.leanix.net/services/pathfinder/v1")  
          .withTokenProviderHost("svc.leanix.net")
          .withApiToken("<apitoken>")
          .build();

        JsonNode factSheet = new GetFactSheetById("<factSheet Id>", "id description")
          .execute(apiClient)
          .get("factSheet");
        System.out.println(factSheet.get("description").textValue());

        Map<String, String> params = new HashMap<>();
        params.put("/description", "Updated description");
        new UpdateFactSheet(factSheet.get("id").textValue(), params).execute(apiClient);
    }

}