Skip to content

client_introspection

etienne-sf edited this page Mar 26, 2021 · 17 revisions

Use GraphQL introspection with the GraphQL client mode

On server side, the introspection is directly managed by graphql-java. There is no additional work to do, to make it work.

On client side, graphql-java-generator makes it easy to execute GraphQL introspection queries. And the query's response is stored in java classes that match the GraphQL introspection schema.

As specified in the GraphQL specification, there are two main queries: __schema and __type.

You can access to the introspection GraphQL capabilities through the _IntrospectionQuery class. This class is generated in the same package as the other classes (see the client exec GraphQL requests page for details).

__typename in GraphQL types

In the generated code, a field named __typename is added into each java class that is actually a GraphQL type. So you can ask for the GraphQL type name of a response with a query request like this one:

		MyQueryType queryType = new MyQueryType(Main.GRAPHQL_ENDPOINT);
		AllFieldCases response = queryType.allFieldCases("{id __typename}", null);

Introspection queries

You can then execute introspection queries like this:

import com.graphql_java_generator.client.introspection.IntrospectionQuery;
import com.graphql_java_generator.client.introspection.__Schema;
import com.graphql_java_generator.client.introspection.__Type;

...

	void myIntrospection() {
		IntrospectionQuery introspectionQuery = new IntrospectionQuery("https://my.graphql.endpoint/path");
		__Schema schema = introspectionQuery.__schema("{types {name fields {name type {name}}}}");
	}

Or

import com.graphql_java_generator.client.introspection.IntrospectionQuery;
import com.graphql_java_generator.client.introspection.__Schema;
import com.graphql_java_generator.client.introspection.__Type;

...

	void myIntrospection() {
		IntrospectionQuery introspectionQuery = new IntrospectionQuery("https://my.graphql.endpoint/path");
		__Type type = introspectionQuery.__type("{name fields {name type {name}}}", "MyGraphQLType");
	}

How the code is generated

When the plugin is in client mode, the introspection capabilities is generated in the same package as the other classes. This is done by applying the GraphQL plugin against the GraphQL introspection schema.

Then a specific query class is created: __IntrospectionQuery

And the String field named ___typename is added as a requested scalar field (if not in the original query), for every java classes that represent a GraphQL type. This __allows deserialization for interfaces and unions: as the typename is known, the json framework knows what is the original type, and can create the proper class during deserialization.

Clone this wiki locally