GraphQL with Java
Learn how to integrate Apito’s GraphQL tools and database API with your Java applications using Apollo Android. This instant API builder provides powerful GraphQL endpoints and build API tool features that work seamlessly with Java projects.
Overview
Apito’s GraphQL API offers type-safe integration with Java applications through Apollo Android client. This open source CMS generates strongly-typed Java models from your GraphQL schema, ensuring compile-time safety and excellent developer experience.
Prerequisites
- Java 8 or higher
- Android Studio or IntelliJ IDEA
- Basic knowledge of GraphQL concepts
- An Apito project with GraphQL API enabled
Installation
Add Apollo Android Gradle Plugin
Add the Apollo Android plugin to your build.gradle file:
Using Plugins DSL (Recommended):
plugins {
id 'com.apollographql.apollo' version '3.8.2'
}
Using Legacy Syntax:
buildscript {
dependencies {
classpath 'com.apollographql.apollo:apollo-gradle-plugin:3.8.2'
}
}
apply plugin: 'com.apollographql.apollo'
Add Runtime Dependencies
Add the Apollo Android runtime dependency:
dependencies {
implementation 'com.apollographql.apollo:apollo-runtime:3.8.2'
implementation 'com.apollographql.apollo:apollo-android-support:3.8.2'
}
Configuration
Download GraphQL Schema
First, download your GraphQL schema from your Apito project:
- Navigate to your Apito Console
- Go to API Explorer section
- Click on GraphQL tab
- Download the schema file as
schema.graphqls - Place it in
src/main/graphql/directory
Configure Apollo
Create an apollo.config.js file in your project root:
module.exports = {
client: {
service: {
name: 'apito-graphql',
url: 'https://api.apito.io/secured/graphql',
headers: {
'X-API-KEY': 'your-api-key-here'
}
}
}
}
Creating GraphQL Queries
Basic Query Example
Create a GraphQL query file in src/main/graphql/:
GetProducts.graphql:
query GetProducts($limit: Int, $offset: Int) {
products(limit: $limit, offset: $offset) {
id
title
description
price
image {
url
}
categories {
id
name
}
}
}
Mutation Example
CreateProduct.graphql:
mutation CreateProduct($input: ProductInput!) {
createProduct(input: $input) {
id
title
description
price
createdAt
}
}
Implementation
Initialize Apollo Client
Create an Apollo client instance in your Java application:
import com.apollographql.apollo.ApolloClient;
import com.apollographql.apollo.api.Response;
import com.apollographql.apollo.exception.ApolloException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
public class ApitoGraphQLClient {
private static final String BASE_URL = "https://api.apito.io/secured/graphql";
private static final String API_KEY = "your-api-key-here";
private ApolloClient apolloClient;
public ApitoGraphQLClient() {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(chain -> {
Request original = chain.request();
Request.Builder builder = original.newBuilder()
.header("X-API-KEY", API_KEY)
.header("Content-Type", "application/json");
Request request = builder.build();
return chain.proceed(request);
})
.build();
apolloClient = ApolloClient.builder()
.serverUrl(BASE_URL)
.okHttpClient(okHttpClient)
.build();
}
public ApolloClient getClient() {
return apolloClient;
}
}
Execute Queries
Fetching Data:
public class ProductService {
private ApitoGraphQLClient graphQLClient;
public ProductService() {
this.graphQLClient = new ApitoGraphQLClient();
}
public void fetchProducts(int limit, int offset) {
GetProductsQuery query = GetProductsQuery.builder()
.limit(limit)
.offset(offset)
.build();
graphQLClient.getClient()
.query(query)
.enqueue(new ApolloCall.Callback<GetProductsQuery.Data>() {
@Override
public void onResponse(@NotNull Response<GetProductsQuery.Data> response) {
if (response.getData() != null) {
List<GetProductsQuery.Product> products = response.getData().products();
// Process your products data
for (GetProductsQuery.Product product : products) {
System.out.println("Product: " + product.title());
System.out.println("Price: $" + product.price());
}
}
}
@Override
public void onFailure(@NotNull ApolloException e) {
System.err.println("GraphQL Error: " + e.getMessage());
}
});
}
}
Execute Mutations
Creating Data:
public void createProduct(String title, String description, double price) {
ProductInput input = ProductInput.builder()
.title(title)
.description(description)
.price(price)
.build();
CreateProductMutation mutation = CreateProductMutation.builder()
.input(input)
.build();
graphQLClient.getClient()
.mutate(mutation)
.enqueue(new ApolloCall.Callback<CreateProductMutation.Data>() {
@Override
public void onResponse(@NotNull Response<CreateProductMutation.Data> response) {
if (response.getData() != null) {
CreateProductMutation.CreateProduct product = response.getData().createProduct();
System.out.println("Created product with ID: " + product.id());
}
}
@Override
public void onFailure(@NotNull ApolloException e) {
System.err.println("Mutation Error: " + e.getMessage());
}
});
}
Error Handling
Implement comprehensive error handling for your GraphQL operations:
public class GraphQLErrorHandler {
public static void handleResponse(Response<?> response) {
if (response.hasErrors()) {
for (Error error : response.getErrors()) {
System.err.println("GraphQL Error: " + error.getMessage());
System.err.println("Error Code: " + error.getExtensions().get("code"));
}
}
if (response.getData() == null) {
System.err.println("No data received from GraphQL API");
}
}
}
Best Practices
1. Connection Management
- Reuse Apollo client instances
- Implement proper connection pooling
- Handle network timeouts appropriately
2. Caching Strategy
// Enable normalized caching
ApolloClient apolloClient = ApolloClient.builder()
.serverUrl(BASE_URL)
.normalizedCache(new LruNormalizedCacheFactory(EvictionPolicy.builder()
.maxSizeBytes(10 * 1024 * 1024) // 10MB cache
.build()))
.build();
3. Type Safety
- Always use generated types from GraphQL schema
- Implement null checks for optional fields
- Validate input data before mutations
Advanced Features
Subscriptions
For real-time updates, implement GraphQL subscriptions:
ProductSubscription subscription = ProductSubscription.builder().build();
graphQLClient.getClient()
.subscribe(subscription)
.execute(new ApolloSubscriptionCall.Callback<ProductSubscription.Data>() {
@Override
public void onResponse(@NotNull Response<ProductSubscription.Data> response) {
// Handle real-time updates
}
@Override
public void onFailure(@NotNull ApolloException e) {
// Handle subscription errors
}
@Override
public void onCompleted() {
// Subscription completed
}
});
Conclusion
Integrating Apito’s GraphQL API with Java applications provides a robust, type-safe solution for data management. This open source API builder offers excellent developer experience with strong typing, efficient caching, and real-time capabilities.
The combination of Apito’s open source CMS and Apollo Android client ensures scalable, maintainable Java applications with powerful GraphQL integration.
Next Steps
- Explore Apito Console for GraphQL schema management
- Learn about Authentication for secure API access
- Check out other Framework Integrations like React, Vue, Angular, and Next.js