Preparing your IDE for GraphQL
Tags: android, graphql, kotlin, mobile
Published: 2021-05-11 17:10:52

This is a third installment in [Android app with Hasura backend - #3] series. With GraphQL engine and database in place, we have working GraphQL server now. Our client of choice is Android for this article. So further into the article I'll setup Intellij / Android Studio to fiddle graphQL backend. Have a new project created or open an existing project to which we will integrate GraphQL.



#### Prerequisite:

Open Settings/Preference and install plugin called [JS GraphQL](https://plugins.jetbrains.com/plugin/8097-js-graphql). This comes in handy while making API calls to the graphQL server.



---

## Getting endpoint and key from Hasura project

This step is specific to Hasura GraphQL. But, if you already have an endpoint, head over to next step. If you don't have an endpoint, I left few at the end of the article.

Open projects list page [here](https://cloud.hasura.io/projects). Copy the endpoint and client secret for your project.



![image-20210511203806967](https://i.imgur.com/ONmAu2K.png)



---



## Quick intro to GraphQL



In a graphql environment, server exposes a single endpoint. Clients will make API calls called `queries` and `mutations` to this endpoint to fetch/post data. 



To start with this, we need to download the schema file from server. This file contains data types and related operations (CRUD). To bridge the gap between server and client there are client libraries that generates these Data/Query/Mutation classes based on the schema. 



<img src="https://i.imgur.com/p8nEJYb.png" alt="image-20210511205938431" style="zoom:50%;" />



With this mental model let's go to the next section, where we integrate Apollo GraphQL to our project.

---

## Adding Apollo GraphQL Client to the project

Apollo client has following features that offload some work at the client end. 

1. Download schema
2. Generate classes (Data/Input/Query/Mutation)
3. Bundled httpClient that makes API call to server



For this article, we scope it down to schema download. Let's add apollo gradle plugin to our app.



In the project level `build.gradle` add apollo to classpath.

```groovy
buildscript {
    ext {
        apollo_version = '2.5.6'
    }
  	...
      
    dependencies {

        ...
       
        classpath("com.apollographql.apollo:apollo-gradle-plugin:$apollo_version")
    }
}
```



In the app level `app/build.gradle`, apply apollo plugin. This is responsible for downloading `schema.json` and generate classes for us.



```groovy
plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'com.apollographql.apollo'
}
```



Apollo plugin comes with a gradle task to download schema. Sadly, it needs a folder to be already there to download schema into. Let's create a folder structure to download the json into. Run this command to create folder structure and download schema.

```shell
## Create folder structure
mkdir -p ./app/src/main/graphql/com/ex2/hasura/gql/

## download schema
./gradlew downloadApolloSchema \
  --endpoint="https://<xxfff>.hasura.app/v1/graphql" \
  --schema="./app/src/main/graphql/com/ex2/hasura/gql/schema.json" \
  --header="x-hasura-admin-secret: <xxxx>"
```



Now we have the schema file to define our queries. Next step is to configure our IDE to consume the endpoint.

---

## Adding graphqlconfig file for IDE

We have the schema file, but IDE doesn't know it is a graph schema. To notify the GraphqlJS plugin that we have schema, we need a config class that points to it. Let's create one.



From project pane, create a file called *queries.graphql* (only extension matters) under `/app/src/main/graphql/com/ex2/hasura/gql/`. Once opened, IDE plugin can identify we're going to write schema. But it'll struggle to provide us with suggestions. So, it'll prompt us for schema file like this.



![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/htmpq51ej3by5iojvp6x.png)



Click on it and in the balloon, click *create .graphqlconfig file*.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/htmpq51ej3by5iojvp6x.png)

Make sure the config file is created next to schema.json file.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/grkr3875cx3m1fcubuqy.png)



Edit the graphQL file to point to proper endpoint and add header. Also ensure the schemaPath is *<u>schema.json</u>*. If you feel like it, give it a nice name. See below.

```json
{
  "name": "Expenses Schema",
  "schemaPath": "schema.json",
  "extensions": {
    "endpoints": {
      "Default GraphQL Endpoint": {
        "url": "endpoint - url - here",
        "headers": {
          "user-agent": "JS GraphQL",
          "x-hasura-admin-secret" : "admin-secret here"
        },
        "introspect": false
      }
    }
  }
}
```



We have a working setup now. Our IDE can play Postman now.

---

## Composing graphql queries

Open the *queries.graphql* file and select the `Default GraphQL Endpoint`. We're good to edit queries with intellisense now.

```graphql
query GetAllExpenses { ## Custom query name - used in code generation

    expenses {         ## query name from schema
        id             ## required fields
        amount
        remarks
        is_income
    }
}
```

Type the above and place cursor in new line next to `is_income`. Press `Ctrl + Space` you should see other fields in suggestion.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p5iku9if7s2r1h6ronwl.png)

---

## Running gql queries

To run a query, place cursor inside the query block and click on run button.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oy1o9tlt7o7c0lx0qv9g.png)

...

Results appear in Query result panel. Use this for API testing before integrating it to the app.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9fb5c7n9cttfldfbizmn.png)



#### I don't have the Hasura setup but eager to try out GraphQL 🙀

Apollo has this endpoint where you can fetch launches. Feel free to use for experiment. 

```
https://apollo-fullstack-tutorial.herokuapp.com/graphql
```



As you have guessed, the `hasura-admin-secret` header is not needed here. Omit it wherever applicable.



Few more endpoints

```
https://countries.trevorblades.com/
https://api.spacex.land/graphql/
https://tmdb.apps.quintero.io/
```



## Endnote:

It was quite a setup to get our IDE running the graphql query. But bear in mind that, we're doing it for one-time and avoid writing RequestBody / Response classes altogether. 



Next time when the server updates the schema, we just have to run the download schema gradle task. Any breaking schema change will be a compile time error and won't crash the app.



In the next article we'll cover code generation and making API call (Finally!!) to our server.