Join us from October 8-10 in New York City to learn the latest tips, trends, and news about GraphQL federation and API platform engineering.Join us for GraphQL Summit 2024 in NYC
Docs
Start for Free

Using Java


This article describes how to use in Java projects.

Use the Java codegen

Apollo Kotlin generates Kotlin code by default, but you can configure it to generate Java code instead:

build.gradle[.kts]
apollo {
service("service") {
generateKotlinModels.set(false)
}
}

The Java runtime

The default runtime for Apollo Kotlin, apollo-runtime, exposes a coroutines / Flow-based API that isn't well suited to be consumed from Java. That is why a specific runtime, apollo-runtime-java is available to use Apollo Kotlin from Java. To use it, add a dependency on this runtime instead of the default one:

build.gradle[.kts]
dependencies {
// ...
// Use apollo-runtime-java instead of apollo-runtime
implementation("com.apollographql.apollo3:apollo-runtime-java:4.0.0-beta.7")
}

Note that the Java runtime currently doesn't support the HTTP or normalized caches.

The Java runtime has a callbacks based API. This snippet demonstrates initializing an ApolloClient and executing a in Java:

import com.apollographql.apollo3.runtime.java.ApolloClient;
// (...)
// Create and configure an ApolloClient
ApolloClient client = ApolloClient.Builder builder = new ApolloClient.Builder()
.serverUrl("https://example.com/graphql")
.build();
// Call enqueue() to execute a query asynchronously
apolloClient.query(new MyQuery()).enqueue(response -> {
if (response.data != null) {
// Handle (potentially partial) data
System.out.println(response.data);
} else {
// Something wrong happened
if (response.exception != null) {
// Handle non-GraphQL errors, e.g. network issues
response.exception.printStackTrace();
} else {
// Handle GraphQL errors in response.errors
System.out.println(response.getErrors().get(0));
}
}
});

Cancelling requests

euqueue returns an ApolloDisposable that can be used to cancel the request:

ApolloDisposable disposable = apolloClient.subscription(new MySubscription()).enqueue(response -> ...)
// ...
disposable.dispose();

Subscriptions

Please refer to the subscriptions documentation for more information about in general, and the available protocols.

When executing subscriptions with the Java runtime, the callback passed to enqueue() can be called several times:

ApolloClient apolloClient = new ApolloClient.Builder()
.serverUrl("https://example.com/graphql")
// Configure a protocol factory
.wsProtocolFactory(new ApolloWsProtocol.Factory())
.build();
// Execute the subscription
ApolloDisposable disposable = apolloClient.subscription(new MySubscription()).enqueue(response -> {
System.out.println(response.dataOrThrow());
});
// Observe the disposable to know when the subscription is terminated
disposable.addListener(() -> {
// Will be called when an operation terminates (either successfully or due to an error)
});

Interceptors

Like the Kotlin runtime, the Java runtime supports interceptors.

  • HTTP interceptors (HttpInterceptor) can be used to add headers to requests (e.g. for authentication), log requests and responses, etc.
  • interceptors (ApolloInterceptor) can be used to modify GraphQL requests and responses, implement retry logic, etc.
// An HTTP interceptor that adds a custom header to each request
HttpInterceptor httpInterceptor = (request, chain, callback) -> {
request = request.newBuilder().addHeader("my-header", "true").build();
chain.proceed(request, callback);
};
// A GraphQL interceptor that logs the name of each operation before executing it
ApolloInterceptor apolloInterceptor = new ApolloInterceptor() {
@Override
public <D extends Operation.Data> void intercept(@NotNull ApolloRequest<D> request, @NotNull ApolloInterceptorChain chain, @NotNull ApolloCallback<D> callback) {
System.out.println("Executing operation: " + request.getOperation().name());
chain.proceed(request, callback);
}
};
// Configure the interceptors when building the ApolloClient
apolloClient = new ApolloClient.Builder()
.serverUrl(...)
.addHttpInterceptor(httpInterceptor)
.addInterceptor(apolloInterceptor)
.build();

If you already have implemented OkHttp interceptors, you can also use them by passing your OkHttpClient instance to the ApolloClient.Builder:

OkHttpClient okHttpClient = new OkHttpClient.Builder()
.okHttpClient(myOkHttpClient)
.build();

RxJava extensions

If your project uses RxJava, you can use Apollo's RxJava with the Java runtime.

To do so, add the apollo-rx2-support-java or apollo-rx3-support-java dependency to your project:

build.gradle[.kts]
dependencies {
// ...
// For RxJava 2
implementation("com.apollographql.apollo3:apollo-rx2-support-java:4.0.0-beta.7")
// For RxJava 3
implementation("com.apollographql.apollo3:apollo-rx3-support-java:4.0.0-beta.7")
}

Then use the Rx2Apollo or Rx3Apollo classes to execute GraphQL and get RxJava observables:

import com.apollographql.apollo3.rx3.java.Rx3Apollo;
// (...)
// Query
ApolloCall<MyQuery.Data> queryCall = client.query(new MyQuery());
Single<ApolloResponse<MyQuery.Data>> queryResponse = Rx3Apollo.single(queryCall);
queryResponse.subscribe( /* ... */ );
// Mutation
ApolloCall<MyMutation.Data> mutationCall = client.mutation(new MyMutation("my-parameter"));
Single<ApolloResponse<MyMutation.Data>> mutationResponse = Rx3Apollo.single(mutationCall);
mutationResponse.subscribe( /* ... */ );
// Subscription
ApolloCall<MySubscription.Data> subscriptionCall = client.subscription(new MySubscription());
Flowable<ApolloResponse<MySubscription.Data>> subscriptionResponse = Rx3Apollo.flowable(subscriptionCall);
subscriptionResponse.subscribe( /* ... */ );
Previous
Using aliases
Next
Apollo AST
Rate articleRateEdit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc.

Privacy Policy

Company