Implementing GraphQL in Android Step by Step.
Overview:
GraphQL is a modern and powerful query language that is quickly gaining popularity in the developer community. It allows developers to efficiently fetch and modify data from APIs by providing a more efficient and intuitive syntax than traditional REST APIs. With its strong type system and flexible nature, GraphQL is quickly becoming the go-to solution for API development. This article will explore how to implement GraphQL in Android and the benefits it provides over traditional REST APIs. By the end of this article, you will have a clear understanding of how to implement GraphQL in your Android application and how it can make your development process more efficient and scalable.
Benefits of GraphQL over Traditional RestAPI:
1- Flexible queries: With GraphQL, clients can request multiple resources in a single query, which can reduce the number of API calls required to retrieve data. Additionally, clients can specify the shape of the response data, allowing them to request only the fields they need.
3- Increased efficiency: GraphQL allows clients to specify exactly what data they need, reducing the amount of data that needs to be transferred over the network. This can significantly improve performance, especially for mobile devices or slow network connections.
4- Strongly typed schema: GraphQL APIs have a strongly typed schema, which allows clients to know exactly what data is available and how to query it. This can improve developer productivity and reduce errors.
Overall GraphQL provides more flexibility and efficiency for data retrieval than REST API, while REST API provides better caching and simpler endpoints. The choice between GraphQL and REST API depends on the specific use case and the trade-offs between flexibility, efficiency, and simplicity.
Using Graphql in android:
After this introduction lets know how to implement it in android
To Communicate with GraphQl server in android we need GraphQL client like ApolloClient.
Apollo Client is a powerful and popular GraphQL client library that is used for building client-side applications. It is an open-source library that provides developers with a range of features and tools for working with GraphQL APIs, such as caching, error handling, and real-time update.
for more details about apolloCLient link to https://www.apollographql.com/docs/kotlin/ .
Steps to Configration:
1- lets begin by Adding ApolloClient Library
# In your project build.gradle add following:
plugins {
id('com.apollographql.apollo3').version '3.7.3' apply false
}
The plugin contains the compiler that will generate models from your queries when you build your project.
# in module build.gradle we need to add following dependencies:
plugins {
// ...
id 'com.apollographql.apollo3'
}
android {
//..
}
dependencies {
//apollo client runtime
implementation "com.apollographql.apollo3:apollo-runtime:3.7.3"
//optional
implementation 'com.apollographql.apollo:apollo-coroutines-support:3.7.3'
}
// at end of gradle we should ad this to specify the package in which the Kotlin files will be generate
apollo {
service("service") {
packageName.set("your app package")
}
}
2- Go to android setting and install GraphQL
the Benefits of this plugin is :
- Schema-aware completion, error highlighting, and documentation
- Syntax highlighting, code-formatting, folding, commenter, and brace-matching
- Execute queries and mutations with variables against configurable endpoints
- Support for multiple schemas using graphql-config
3- create one new directory in app’s “main” package named “graphql”:
Inside this Directory you must put your schema.json here and all your queries againts sever will be under graphql folder.
lets for example use rickandmorty graphql Api , link below https://rickandmortyapi.com/graphql .
we first download schema.json of our Graph server in our local
You can download a schema using introspection with the ./gradlew downloadApolloSchema
task
./gradlew downloadApolloSchema --endpoint="https://rickandmortyapi.com/graphql" --schema="src/main/graphql/schema.json"
if your Graphql server require Authenication you can pass header like this:
./gradlew downloadApolloSchema \
--endpoint="https://rickandmortyapi.com/graphql"
--schema="app/src/main/graphql/schema.json"
--header="Authorization: Bearer $TOKEN"
OR you can even download it using Apollo Cli via terminal
>> apollo schema:download — endpoint=https://rickandmortyapi.com/graphql schema.json.
after download schema manual using cli you can copy and paste it under main->graphql folder .
Now The Time for writing query
4- After download schema you are ready to write your queries:
to write query you can use helping tools like postman insomnia or graphql playground online.
so right now I’m going to use online Graphql playground to write my first query.
hit the link below and it will direct you to playground and start typing your query..
https://rickandmortyapi.com/graphql
You can see in the above image , the left side represent your schema doc and middle is query that I made to get characters with their location and the result presented in right section.
if you note I made nested query in one call as I fetched characters with their location, if we need to do that in Rest Api we have to make another Api call to fetch characters location.
and this is one of benefits of Graph over Traditional Rest Api that we mentioned above.
so after you tested your query then copy the query and go to android project under main->graphql folder with schema.json and make .graphql file
lets name it GetAllCharacters.graphql and paste your code there.
then rebuild your project and you will see the koltin generated classes corresponding to query ,under app->java genereted classes looks like this .
If you get this Congrats you are mostly Done and you are One step further to final result.
The last is to execute your query against GraphQL server.
we need to create instance from apolloClient.
5- Create instance from ApolloClient:
// Create a client instance
const val BASE_URL="https://rickandmortyapi.com/graphql"
val apolloClient = ApolloClient.Builder()
.serverUrl(BASE_URL)
.build()
Note:This is not good practise to create instance as you know but we are just need to learn with simple example.
/ Execute your query
viewModelScope.launch {
val response = apolloClient.query(GetCharactersQuery(page = 1,"Morty")).execute()
Log.d("TAG", "response: ${response.data?.characters}")
}
you will get the result below
You are done..
Conclusion:
This is just very simple example to setup and use graphql in android ,in upcomming articles we will deep dive and learn how to use couroutine, hilt and caching with apollo client and make complete app so be tuned , Thanks a lot for reading and give it clap if find it informative.