How to use Apollo GraphQL in Android Kotlin

GraphQL is a query language for APIs that allows you to specify the data you want from a server in a declarative way. Apollo GraphQL is a popular GraphQL client that generates Kotlin and Java models from GraphQL queries and executes them against a GraphQL server. In this blog post, I will show you how to set up Apollo GraphQL in your Android Kotlin project and how to use it to perform queries, mutations and subscriptions.

Setting up Apollo GraphQL

To use Apollo GraphQL in your Android Kotlin project, you need to add the following dependencies to your build.gradle.kts file:

plugins { id("com.apollographql.apollo3") version "3.8.1" } dependencies { implementation("com.apollographql.apollo3:apollo-runtime:3.8.1") }

You also need to set the package name for the generated models in your apollo block:

apollo { service("service") { packageName.set("com.example") } }

Apollo GraphQL supports three types of files:

  • .graphqls schema files: describe the types in your backend using the GraphQL syntax.
  • .json schema files: describe the types in your backend using the JSON syntax.
  • .graphql executable files: describe your queries and operations in the GraphQL syntax.

By default, Apollo GraphQL requires a schema in your module’s src/main/graphql directory. You can download a schema using introspection with the ./gradlew downloadApolloSchema task.

Writing and executing queries

To write a query, you need to create a .graphql file in your src/main/graphql directory with the following syntax:

query GetPosts($limit: Int) { posts(limit: $limit) { id title author { name } } }

This query will fetch a list of posts with their id, title and author name, and accept a limit argument to limit the number of posts.

Apollo GraphQL will generate a Kotlin class for this query with the same name as the file (GetPostsQuery) and a data class for each type (Post, Author). You can use these classes to execute the query using an ApolloClient instance:

val apolloClient = ApolloClient.Builder() .serverUrl("https://example.com/graphql") .build() val query = GetPostsQuery(limit = 10) apolloClient.query(query).execute().let { response -> if (response.isSuccessfull) { // handle success val posts = response.data?.posts // do something with posts } else { // handle error val error = response.errors?.firstOrNull() // do something with error } }

The execute() method returns an ApolloResponse object that contains either data or errors. You can access the data as query-specific Kotlin types and handle any errors that may occur.

Writing and executing mutations

To write a mutation, you need to create a .graphql file in your src/main/graphql directory with the following syntax:

mutation CreatePost($title: String!, $authorId: ID!) { createPost(input: {title: $title, authorId: $authorId}) { id title author { name } } }

This mutation will create a new post with the given title and author id, and return the created post with its id, title and author name.

Apollo GraphQL will generate a Kotlin class for this mutation with the same name as the file (CreatePostMutation) and a data class for each type (Post, Author). You can use these classes to execute the mutation using an ApolloClient instance:

val apolloClient = ApolloClient.Builder() .serverUrl("https://example.com/graphql") .build() val mutation = CreatePostMutation(title = "Hello world", authorId = "1") apolloClient.mutate(mutation).execute().let { response -> if (response.isSuccessfull) { // handle success val post = response.data?.createPost // do something with post } else { // handle error val error = response.errors?.firstOrNull() // do something with error } }

The execute() method returns an ApolloResponse object that contains either data or errors. You can access the data as mutation-specific Kotlin types and handle any errors that may occur.

Writing and executing subscriptions

To write a subscription, you need to create a .graphql file in your src/main/graphql directory with the following syntax:

subscription OnPostCreated { postCreated { id title author { name } } }

This subscription will listen for new posts created on the server and return the new post with its id, title and author name.

Apollo GraphQL will generate a Kotlin class for this subscription with the same name as the file (OnPostCreatedSubscription) and a data class for each type (Post, Author). You can use these classes to execute the subscription using an ApolloClient instance:

val apolloClient = ApolloClient.Builder() .serverUrl("wss://example.com/graphql") .build() val subscription = OnPostCreatedSubscription() apolloClient.subscribe(subscription).execute().collect { response -> if (response.isSuccessfull) { // handle success val post = response.data?.postCreated // do something with post } else { // handle error val error = response.errors?.firstOrNull() // do something with error } }

The execute() method returns a Flow of ApolloResponse objects that emit data or errors. You can collect the data as subscription-specific Kotlin types and handle any errors that may occur.

Conclusion

In this blog post, I showed you how to use Apollo GraphQL in your Android Kotlin project and how to perform queries, mutations and subscriptions. Apollo GraphQL is a powerful and type-safe GraphQL client that makes it easy to work with GraphQL APIs. You can learn more about Apollo GraphQL from their official documentation12 or their GitHub repository3. I hope you enjoyed this blog post and found it useful. Happy coding! 🚀


How did I do? 😊

Author: John Rowan

I am a Senior Android Engineer and I love everything to do with computers. My specialty is Android programming but I actually love to code in any language specifically learning new things.

Author: John Rowan

I am a Senior Android Engineer and I love everything to do with computers. My specialty is Android programming but I actually love to code in any language specifically learning new things.

%d bloggers like this: