MindInventory

In this blog, I’ll give information about GraphQL in the simplest possible way followed by how we can consume the GraphQL APIs from android. You will understand,

  1. What is GraphQL?
  2. What benefits does it serve that REST API couldn’t?
  3. Set up/ Implementation.
  4. How to write Query to attain only required data from backend services?

For your better understanding, I’ve created a small simple android application, using the Apollo library to fetch data from the Rick and Morty GraphQL endpoint. Yes, just that simple thing that will help you start with GraphQL.

Overview:

A short introduction to the keywords we will use in this blog.

GraphQL

GraphQL is a query language (that’s what the “QL” stands for) for APIs and a runtime for fulfilling those queries with your existing data. Basically, it is used to load data from a server to a client.

Apollo Android

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

Schema.sdl 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. Schema file can have an extension of json | sdl.

*.graphql File:

For query requests, we need to create a .graphql extension file and keep it in the android project folder. Apollo Android will use this and schema.sdl file for generating the POJO classes of each query file. (be with me, I’ll show this later in this blog).

I am a big fan of “Always Start with WHY”, so let’s do that.

In Summary: Why GraphQL?

The 3 most important problems that GraphQL solves gracefully are:

  • Multiple round trips to fetch data required by a view: GraphQL lets you specify exactly what you need, and then it fetches just that with a single round-trip to the server — nothing more, nothing less. To do the same with a REST API, we needed to make multiple API calls.
  • Clients dependency on servers: With GraphQL, the client speaks a request language, which eliminates the need for the server to hardcode the shape or size of the data, as the client will get the only data that they ask for.
  • The bad front-end developer experience: With GraphQL, developers express the data requirements of their user interfaces using a declarative language and get the data that they asked for in a single request, which saves Time and Bandwidth. Wherewith REST, the user gets all the data defined in the backend that the user may not even need. That’s called “Over-fetching” in the GraphQL term.

The Explain-GraphQL-like-I’m-5 version…

  • GraphQL is all about data communication.
  • You have a client and a server and both of them need to talk with each other. The client needs to tell the server what data it needs, and the server needs to fulfill this client’s data requirement with actual data. GraphQL steps into the middle of this communication.

Why keep GraphQL in the middle, what are the benefits of it?

1. Efficiency:

  • The client usually needs to make multiple round-trips to the server, as at a time server usually understands how to reply with a single resource only.
  • With GraphQL, we can basically shift this multi-request complexity to the server-side and have the GraphQL layer deal with it. The client asks the GraphQL layer a single question and gets a single response that has exactly what the client needs.

2. Communicating with multiple services:

Screenshot captured from Samer Buna’s Pluralsight course — Building Scalable APIs with GraphQL
  • For example, Instead of a client going to the two different data services directly,

1. Client communicates with just the GraphQL layer.

2. GraphQL layer will do the communication with the two different data services.

  • Thanks to the GraphQL layer, clients don’t have to communicate in multiple languages
  • Simply put, the Client just needs to make a single data request to the GraphQL layer, and the layer will handle the request and translation of the request to multiple servers.

Imagine that you have three people who speaks three different languages and have different types of knowledge. Now imagine that you have a question that can only be answered by combining the knowledge of all three of them together. If you have a translator who speaks all three languages, the task of putting together an answer to your question becomes easy. This is exactly what a GraphQL runtime does.

3. Fixed set of schema requests, that client knows in prior:

  • The GraphQL server uses a GraphQL schema to define and describe the shape of your data graph.
  • In simple words, Schema represents the limits of what can be answered by the GraphQL layer.
  • Computers aren’t smart enough to answer just any questions (at least not yet), Actually they have to follow an algorithm somewhere. This is why we need to define a schema on the GraphQL runtime and that schema gets used by the clients.

4. Strongly-typed Schema:

  • All types such as Boolean, String, Int, Float, ID, Scalar which are supported by the API are specified in the schema in GraphQL Schema Definition Language (SDL), which helps the client to determine which data are available.

5. Saves Time and Bandwidth:

  • Allows making multiple resources request in a single query call, which saves a lot of time and bandwidth by reducing the number of network round trips to the server.

6. Versioning Is Not Required:

  • Due to changes in resources or the request/response structure of the resources developers needed to create new versions (E.g. api.domain.com/v1/, api.domain.com/v2/) In REST architecture.
  • But in GraphQl, no need to maintain versions. The resource URL or address remains the same. You can re-download the updated schema file. You can add new fields and deprecate older fields as per your need.
  • This approach is intuitive as the client receives a deprecation warning when querying a deprecated field.

7. No Over-Fetching or Under-Fetching:

  • fetch only what is required.
  • Over-fetching happens when the response fetches more than what is required or fetches unnecessary data. This impacts the performance of your app and consumes more data, which is expensive for the user.
  • Under-fetching is not fetching adequate data in a single API request. In this case, you need to make multiple API requests to get the required data.

How GraphQL is different from REST?

In order to make a REST API call, we use HTTP methods like GET, POST, PUT and DELETE but in the case of GraphQL, uses a different approach, Named Query, Mutation, and Subscription.

For more information on these approaches, refer to this blog —

Start new project

Go to Android Studio and create a new Empty Project (with Kotlin)

head to app-level build.gradle, add the first line add plugins for the needed dependencies:

plugins {
id ‘com.android.application’
id ‘kotlin-android’
id ‘kotlin-kapt’
id(“com.apollographql.apollo”).version(“2.5.9”)
}

Now add the following dependency which is from Apollo library which converts *.graphql files into *.kt file. It should be in the same hierarchy as android {}.

apollo {
// instruct the compiler to generate Kotlin models
generateKotlinModels.set(true)
}

Creation of GraphQL schema :

GraphQL schema defines what types of data a client can read and write to your graph.

Navigate now from app -> src -> main. Right-click on main -> New -> Directory

Create a new directory and name it graphql. Create the same sub-directories as in your java folder.

This is important because now we will save the schema.sdl file and also add the *.graphql files there. The same package structure is important as it will make use of generated Kotlin classes in the java package easy.

JS GraphQL Android Studio Plugin

Add Js graphQl plugin from Android Marketplace.

Now add the empty schema.sdl file, inside package structure: graphql -> com -> example -> apollographqltutorial -> right click -> New -> File -> schema.sdl

The plugin helps to detect local Schema.

Built-in support for Relay and Apollo projects:

graphql and gql tagged template literals are automatically recognized as GraphQL

At compile time it shows possible suggestions while forming Query.

Syntax highlighting, code-formatting, folding, commenter, and brace-matching are the features that this plugin provides.

That’s it for the first part. Stay tuned with us for more interesting advanced coding recipes, until we publish the next blog on fetching data from a GraphQL endpoint. If you enjoyed this blog give it a clap.

--

--