GraphQL With Android in Kotlin

Vishal Pandey
5 min readOct 11, 2019

--

Hello Techies,

Are you an Android Developer?🤓 Got a requirement for consuming GraphQL APIs? Congratulations!!! you are at the right bus stop 🛑.
In this article, I'll give short information about GraphQL followed by how we can consume the GraphQL APIs from android. For your better learning, I've created a small android application that will list all the countries based on selected continents and the repository link is attached below.
Excited?? 😊 Then let’s kick-off 🤘

Overview:

A short introduction to the keywords we will use in this article.
GraphQL:
is a query language for API, and a server-side runtime for executing queries by using a type system you define for your data. GraphQL isn’t tied to any specific database or storage engine and is instead backed by your existing code and data.

Apollo Android:
is a GraphQL client for Android, we can use Apollo client with Okhttp. Apollo Android is responsible for generating the Java classes based on defined GraphQL query (don’t panic now will prove this step by step later).

Schema.json File:
For every GraphQL server, we have a schema.json file that will define the schema of the GraphQL server. Before making any GraphQL API request we need this file to be downloaded and stored in our project folder. Make sure this file is generated correctly, otherwise you will get an error from Apollo.

My_query.graphql File: For query requests, we need to create a .graphql extension file and keep in the android project folder. Apollo Android will use this and schema.json file for generating the POJO classes of each query file. (be with me, I'll show this later in this article).
I think we are good to start with the actual implementation.

Implementation:

  • Step One -
    Download node from here so that we can use npm for installing the apollo package(used for downloading schema.json file).
  • Step Two -
    There are lots of GraphQL APIs you can consume form Android, see here. For my project, I’m using https://countries.trevorblades.com
  • Step Three -
    Download the schema.json for GraphQL.
sudo npm install -g apolloapollo schema:download --endpoint=https://countries.trevorblades.com schema.jsonOptional --header parameter(this is not required for our project)

apollo schema:download --endpoint=graphql_url schema.json
--header="Authorization:Bearer token_here"

(here --header is mandatory for github graphql api but not for all apis)
  • Step Four -
    Create a new android project, setup Gradle dependencies for apollo android support and android Gradle plugin.
Inside project build.gradle
____________________________________________________________________
buildscript {
...
repositories {
google()
jcenter()
mavenCentral() // Make sure this is added
}
dependencies {
classpath "com.apollographql.apollo:apollo-gradle-plugin:1.0.0
}
}
Inside app build.gradle
____________________________________________________________________
apply plugin: 'com.apollographql.android' //Add this
android {
...
}
dependencies {
implementation "com.apollographql.apollo:apollo-runtime:1.0.0"
implementation
"com.apollographql.apollo:apollo-android-support:1.0.0"
}
}
  • Step Five -
    Create your .graqphql file for querying to the server. Here in our project two queries are required(one for getting the list of continents and the other for getting the list of countries based on the passed continent), so I’ve created two files.
getAllContinents.graphql
____________________________________________________________________
query GetContinents{
continents {
code
name
}
}
getContriesName.graphql
____________________________________________________________________
query FindContriesOfAContinent($code:String!){
continent(code: $code) {
countries {
name
native
phone
currency
emoji
}
}
}
  • Step Six -
    Create a folder named graphql inside src/main and create a package, then paste schema.json file(step 3) and both .graphql files(step five) inside graphql folder.
  • Step Seven -
    If everything is fine till the last step, then rebuild the project(build->Rebuiuld Project). If the build is successful then apollo will generate the helper class for both the files(created in step five). Classes will be generated in path build/generated/source/apollo/classes/package_name_created_in_step_six. Let me know if you face any error, will reply ASAP.

Congratulation!!! and thanks for your patience, you are done with the graphql setup for android(Android Apollo), now API consumption will be done with Okhttp and Apollo client.
In this application, the first API will be called(
getAllContinents.graphql) for getting all the continents and set the data to a drop-down(Spinner view of Android). Now when the user will select any continent from the drop-down second API(getContriesName.graphql) will be called, and in the response to that country's list will be shown.

private fun setUpApolloClient(): ApolloClient { 
val logging = HttpLoggingInterceptor()
logging.level = HttpLoggingInterceptor.Level.BODY
val okHttp = OkHttpClient
.Builder()
.addInterceptor(logging)
return ApolloClient.builder()
.serverUrl(BASE_URL)
.okHttpClient(okHttp.build()) //ApolloClient with okhttp
.build()
}

For making things simple I’ve created only one activity where all API call and UI populations happening, if you want to learn about MVP design pattern then I would recommend you check my other article here.

Bonus(Don’t miss this):

This is more of the Android side code for GraphQL. Now I’ll request you to please visit https://countries.trevorblades.com and paste my queries defined in step-four and test how Graphql queries work. Towards the right of the page, you will find the DOCS tab expand that and tweak through the queries.

As getAllContinents.graphql doesn’t require any query variable so we will call it directly.

ListCountriesActivity.ktclient.query(
GetContinentsQuery
.builder()
.build()
)

But in getContriesName.graphql we need to pass the continent code for getting the countries list, So we need to pass the code as a query variable.

ListCountriesActivity.ktclient.query(
FindContriesOfAContinentQuery
.builder()
.code(code?.let { code }) // passing the code variable
.build()
)

For Graphql editor(https://countries.trevorblades.com) You can pass the same query variable from the bottom of the page.

That’s all from my side about Android Graphql with apollo, let me know if you have any problem with this post.
Cheers!!! 🍻 Happy Coding!!!😎 Happy to Help!!!🙌🏼

--

--

Vishal Pandey

JAVA | Kotlin | Android | React | Spring Boot| Graphql