Nerd For Tech
Published in

Nerd For Tech

Android Tutorial Part 2: Using Apollo library to fetch data from a GraphQL endpoint

Photo by NASA on Unsplash

GraphQL information

In Part 1, we configured the project structure and added an empty schema.sdl file.

Okay, I think it is time to explain some things. When you are using GraphQL there is only one endpoint for CRUD operations. Therefore we have to save a schema file locally for all operations. For fetching data you need a query{}, for creating/updating data you need a mutation{} and for getting updates about specific data changes you need subscription{}. For this tutorial, we will only use query{}.

Get the schema

Remember our schema.sdl is currently empty, now let’s get the schema. First, open GraphQL Playground here is the link: https://www.graphqlbin.com/v2/new

Paste in the GraphQL Playground the Rick and Morty API link: https://rickandmortyapi.com/graphql

When the playground is open, you will see on the right side two tabs: DOCS and SCHEMA. Click on SCHEMA

Mark everything and copy it and paste everything in your schema.sdl file in Android Studio. Your schema.sdl should look like this:

Just for fun info :)

You can also download the schema file. The SCHEMA tab has on the right side a download button, where you can decide between JSON or SDL.

Sometimes the downloaded file has some problems, that’s why I prefer the copy/paste approach. If you ever should use an Apollo version that is older than 2.5.4 like 2.2.0 then you can’t use SDL, because the generator can’t recognize the file type.

Write your first query

Time to look at what to query. Click on the tab DOCS. Now, you should see all the query options. You can click on each entry to see what you can query. Take a look at “characters” and click through the possible query options.

There we see that characters leads to results and this leads to character details. So this means the query has hierarchical structure, first characters{} this leads to characters { results {} } this finally leads to characters { results { id name species } }

Jump now to the left panel and write the following query:

query CharactersList {
characters {
results {
id
name
species
}
}
}

The query name is “CharactersList” for Apollo to generate a Kotlin file. We have to give the query a name. The next lines describe what we want to query. This leads to a list of characters with id, name and species. Obviously, I could fetch more or less than id, name and species. But we will fetch more in the next steps. Press now the play button to see if your query correct.

When you see a data output you know your query is correct. Jump back now to Android Studio. Create in the same package like your schema.sdl a new file. The file has the name of your query, so create CharactersList.graphql

Copy your query from the left panel of the playground and paste it in your CharactersList.graphql file.

Click now on Build -> Clean Project then click on Build -> Rebuild Project.

Time to see if Apollo could create a Kotlin file of the CharactersList.graphql file. If you are using a MacOS then double click on shift and search for “CharactersListQuery”.

Open the file CharactersListQuery. There you will find a Result data class with fields we need for our list query.

public data class Result(
public val __typename: String = "Character",
public val id: String?,
public val name: String?,
public val species: String?
)

This means we can start developing the app, you can close again the generated file CharactersListQuery.

Start developing the app

In the same package where MainActivity is stored, create a new file: RickAndMortyApp. Inherit from Application() and annotate the class with HiltAndroidApp so Hilt can create from there the dependency tree for your app.

@HiltAndroidApp
class RickAndMortyApp : Application()

Move to AndroidManifest.xml first add the permission for the Internet. After that give your application name RickAndMortyApp.

<uses-permission android:name="android.permission.INTERNET" />

<application
android:name=".RickAndMortyApp"
android:allowBackup="true"
...

Repository for fetching data

It is time to create a repo for fetching the data. Create a new package and name it repository. Create the interface CharacterRepository and create a suspend function which has a return type of: Response<CharactersListQuery.Data>

Place the cursor inside CharacterRepository and press ALT + Enter and move to “Implement Interface”. Then you should have a class CharacterRepositoryImpl.

The GraphQL client

The next class we need is an instance of the ApolloClient. Before implementing the CharacterRepositoryImpl let us implement the class for the ApolloClient. Create a new package and name it networking. Create there a class RickAndMortyApi.

class RickAndMortyApi {

fun getApolloClient(): ApolloClient {
check(Looper.myLooper() == Looper.getMainLooper()) {
"Only the main thread can get the apolloClient instance"
}

val okHttpClient = OkHttpClient.Builder().build()
return ApolloClient.builder()
.serverUrl("https://rickandmortyapi.com/graphql")
.okHttpClient(okHttpClient)
.build()
}

}

As you can see this class creates the ApolloClient and does the network call to the Rick and Morty API endpoint.

Okay, that’s it for the second part. If you enjoyed this article give it a clap. Here is Part 3.

Here is the completed project, check out branch part_two

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store