How to make GraphQL request in Android using Kotlin
In this article I am going to demonstrate how to make a GraphQL request using android. With android I am using below libraries and technologies.
Kotlin programming language
Retrofit and Kotlin Coroutines to make api calls
Dagger 2 for dependency injection
I expect you are aware of above technologies to understand this article. Therefore I focus mainly on making a request using GraphQL and to discuss about what is GraphQL and why it came.
Before there was GraphQL, there was REST. Below are some downsides of REST which GraphQL comes with answers.
- Over-fetching
- Multiple requests for multiple resources
- Waterfall network requests on nested data
- Each client need to know the location of each service
- API versioning becomes a hassle sometimes
What is GraphQL ?
GraphQL is a query language and server-side runtime for APIs that prioritizes giving clients exactly the data they request and no more. — Red Hat
Here mark the word “query language”. Because of that we can query what we want.
When to use GraphQL ?
- Apps for devices such as mobile phones, smartwatches, and IoT devices, where bandwidth usage matters.
- Applications where nested data needs to be fetched in a single call.(For example, a blog or social networking platform where posts need to be fetched along with nested comments and commenters details.)
- Where application retrieves data from multiple, different storage APIs.(For example, a dashboard that fetches data from multiple sources such as logging services, backends for consumption stats, third-party analytics tools to capture end-user interactions etc.)
Let’s go coding !
I will be using github GraphQL APIs which is available for anyone and can use to try GraphQL queries associated with existing github repositories. Here I will try to fetch and display main user information (image, name, login, email, followers, following), 3 first of pinned repositories and10 first of top repositories of a selected user in github. you can use github explorer to test your graphql queries.
Full code can be found from this github url.
First add following dependencies in your app level build.gradle file.
Below is my query to fetch above mentioned user data.
To use this in your application you need to get a github token. to get it go to this link and click on “Generate new token”. I have added my token and query in a constant file as follows.
Now write the Retrofit interface.
Now we will do Dependency injection with Dagger2
Create NetModule class to provide gson and retrofit dependencies
Add NetModule in AppComponent interface
Build your appcomponent in Application class
Then call it and get data.
Above “retrofit” and “gson” are taken by injecting it to the class using Dagger 2.
Result will be as follows.
Thanks! Find the full code from github.