Was this page helpful?

Using Contentful GraphQL With Android

In order to pull data from the new Contentful GraphQL endpoint (now in Beta), Apollo for Android Client can be used.

Overview

The workflow when working with a GraphQL endpoint and the Apollo SDK is as follows:

  • Using the Apollo CLI to introspect the GraphQL schema to include the content model in the project.
  • Write and test queries using GraphiQL.
  • Use the Apollo plugin to generate model types from the schema and queries.
  • Integrate ApolloClient into the app, passing in the generated queries; write the logic for handling already-parsed responses.

Setup

Installing dependencies can be achieved by adding the following statements to the root build.gradle file:

buildscript {
    repositories {
        // … (other values from the project)
        jcenter()
    }
    dependencies {
        // … (other values from the project)
        classpath 'com.apollographql.apollo:apollo-gradle-plugin:1.0.0-alpha2'
    }
}

The application specific build.gradle needs to load the plugin and depend on the runtime libraries:

// … other apply statements, apollo needs to be last
apply plugin: 'com.apollographql.android'

dependencies {
    // … more implementation statments
    implementation 'com.apollographql.apollo:apollo-runtime:1.0.0-alpha2'
}

Once dependencies have been declared, setup is done by providing the authorization header. The following is an example of doing so:

val httpClient: OkHttpClient = OkHttpClient
   .Builder()
   .addInterceptor { chain ->
       chain.proceed(
           chain.request().newBuilder().addHeader(
               "Authorization",
               "Bearer $token"
           ).build()
       )
   }
   .build()

ApolloClient
   .builder()
   .serverUrl("https://graphql.contentful.com/content/v1/spaces/$space?locale=$locale")
   .callFactory { request ->
       httpClient.newCall(request)
   }
   .build()

Additionally, the snippet above sets the Space and the Locale to be used by the client.

Schema downloading

For generating the java models, a GraphQL schema and a query is required. The schema can be generated by using the apollo cli, which can be obtained from the Apollo CLI GitHub page:

apollo schema:download --header "Authorization: Bearer $TOKEN" --endpoint "https://graphql.contentful.com/content/v1/spaces/$SPACE_ID"

Queries

The following is an example of a sample query for GraphQL:

query Courses { 
  courseCollection { 
    items { 
      title 
    } 
  } 
}

The query can be edited in GraphiQL here. If a query for a custom space is to be used, a link like this needs to be created: https://graphql.contentful.com/content/v1/spaces/${SPACE_ID}/explore?access_token=${ACCESS_TOKEN}. ${SPACE_ID} and ${ACCESS_TOKEN} need to be replaced with the custom credentials.

Model generation

By using Apollo for Android and placing this query and the schema in the right folder (i.e. /app/src/main/graphql/com/contentful/tea/kotlin/content/graphql), the apollo plugin creates classes that can be used for querying.

The following is an example of the query created by using the above mentioned classes :

apollo.query(CoursesQuery.builder().build())
    .enqueue(object : ApolloCall.Callback<CoursesQuery.Data>() {
        override fun onFailure(e: ApolloException) {
            // error
        }

        override fun onResponse(response: Response<CoursesQuery.Data>) {
            if (response.data() != null) {
                    // response.data()?.courseCollection()?.items
            )
        }
    })

In the onResponse method, the data is stored in data()?.courseCollection()?.items and can be redirected for view model generation.

Next steps

This concludes the basic explanation of using GraphQL with Contentful and Android. For further examination, refer to the example Android app using GraphQL.