The following is the first few sections of a chapter from The Busy Coder's Guide to Android Development, plus headings for the remaining major sections, to give you an idea about the content of the chapter.


GraphQL Test Environments

The GraphQL server that we have been using – https://graphql-demo.commonsware.com/0.2/graphql — only supports queries, off of a read-only data set. This prevents trolls from going in and adding… “interesting” data to the server, for some definition of “interesting”.

However, that server lacks any support for mutations, and those are a critical piece of most GraphQL environments. And while it is set up to demonstrate a range of GraphQL capabilities, it does not cover everything.

In this chapter, we will get you set up with two additional environments for trying out GraphQL:

The Test Server

Not only can you access the GraphQL demo server mentioned at the outset of this chapter, but also you can run the same server locally in your environment, such as on your development machine. The advantage is that the local copy can support mutations.

Setting up a local test server is optional. For example, IT rules may prohibit you from installing such a piece of software. However, that will mean that sample code that performs mutations will not work for you — you will be restricted to those samples that only perform queries.

Our Local Server: Express

There are a variety of server frameworks for implementing GraphQL endpoints. At this point, it is fairly likely that there is some server framework available in a programming language that is comfortable for you. The GraphQL Web site lists many libraries and tools for GraphQL, many of which represent server frameworks. C. T. Lin’s awesome-graphql GitHub repo lists even more.

The test server used in this book is implemented using express-graphql. This is the reference implementation of a GraphQL server, maintained by the core GraphQL team. express-graphql is written in JavaScript, designed to be used by Node.js and Express.

Since this is a “canned” server — you do not need to understand its implementation to use it — you should be able to set up and run the server even if you have limited experience with JavaScript.

Where to Run the Server

The simplest solution is to run the test server on your development machine. The test server is designed to be started and stopped from the command line, so you can run the server when you need it for testing and stop it when you no longer need it.

The key is that Android environments running your client code need to be able to reach the server. Depending on your network setup, that may or may not work with your development machine. For example, it may be that you are using a wired desktop, and it is on a separate LAN segment than is the WiFi that your test Android devices use.

express-graphql and its dependencies — including Node.js — are relatively lightweight. You can run the server on a wide range of environments, including a Raspberry Pi running Linux. So, if network restrictions prevent you from running the server on your development machine, you may be able to “get creative” about where your server code runs.

What you do not want to do is take this test server and put it on the public Internet, unless you are willing to take on the burdens of ensuring that only authorized parties can somehow get to that server.

Installing the Server

Setting up the test server is not especially difficult… once you get Node.js going.

Install Node.js

Node.js, if you are not familiar with it, is a framework for using JavaScript as an ordinary programming language, not just something that is used by Web browsers. In particular, Node.js is used for the server side of Web apps, allowing for a “full stack developer” to stick to a single programming language. Node.js uses Google’s V8 engine for its JavaScript environment.

The test server has been tested with Node.js 6.11.0, which is on the long-term support (LTS) update track. It should work with anything in the 6.x versions, and it may work with newer versions of Node.js as well, though this has not been tested.

There are many different possible ways to install Node.js, depending on your operating system, whether you want multiple versions of Node.js to be available, whether you are deploying to a container (e.g., Docker) or not, and so on. This is not a Node.js book, and the author of this book is so not a Node.js expert. The Node.js downloads page is a good starting point for learning how to install Node.js.

When you are done, you should have node and npm commands available to you from the command line.

Obtain the Server Scripts

The test server consists of three files, both in the Trips/Local/ directory of the book’s git repo:

The first two represent the actual server itself; the package.json file provides information about the dependencies on which those JavaScript files rely.

Download all three of these to a clean directory on your development machine or wherever you are planning on running the server.

These files will get updated from time to time. If you get an update to this book, be sure to update to the corresponding version of these files. The links shown above are to the master branch. Each book update’s code in the git repo will be tagged with an equivalent version number (e.g., version 1.0 of the book results in a 1.0 tag in the repo), so you can download the right code to match your book version. There will also be an additional file per release, with the version number embedded in the filename (e.g., server-v0.1.js), with the particular GraphQL server logic that corresponds with that edition of the book.

Install Dependencies

The test server script relies on several dependencies. The package.json file lists them, along with compatible-version information, a bit reminiscent of how the dependencies closure works in Gradle.

Node.js, however, does not automatically download dependencies, any more than running an Android app downloads its dependencies. There is no compilation step with Node.js and JavaScript, though, so the dependency-download step is not handled there, the way it is with Gradle and Android apps.

So, you need to run a single command to download those dependencies:

npm install --save

That will create a node_modules/ directory alongside the server.js and package.json files. In there, you will see a long list of directories representing Node.js packages (npm is the Node package manager). Some will be the dependencies listed in package.json; the rest will be transitive dependencies (the dependencies of your dependencies).

Running the Server

At this point, running the server is merely a matter of running node server.js from the directory where you downloaded server.js and ran the npm install --save command.

You should see a message like Running a GraphQL API server at localhost:4000. Press Ctrl-C to stop the server.

The port number — 4000 — is in the server.js code, towards the bottom, in case you need to change it to some other value.

One command-line switch is offered: --hosted. The presence or absence of this switch controls your starting data and mutation support:

Switch Starting Data Supports Mutations?
--hosted yes no
none none yes

The examples in the book that use this test server assume that you are running without the --hosted switch, and so there will be no starting data, but mutations are available.

Testing with GraphiQL

At this point, you can bring up http://localhost:4000/0.2/graphql in a Web browser and see a copy of GraphiQL for your local copy of the test server:

GraphiQL from Test Server
Figure 10: GraphiQL from Test Server

And, if you run some simple query, you will see that you have no data:

GraphiQL from Test Server, With Empty Results
Figure 11: GraphiQL from Test Server, With Empty Results

When we start working with mutations, we will switch to your test server, so you can see how mutations work. Note, though, that the server does not persist any of the data that you submit — it is merely held in RAM. When you stop and start the server, you wipe out any previous mutation results.

In other words, do not store the travel plans for your real upcoming vacation in this server.

The 0.2/ path segment corresponds with this version of the book. Future versions of the book will have their own GraphQL logic and corresponding paths.

Trying a Mutation

Part of what we gain by having the local test server is the ability to perform mutations.

So, in the GraphiQL tool for your local test server, enter the following GraphQL document:

mutation createTrip($trip: TripInput!) {
  createTrip(trip: $trip) {
    id
  }
}

If you try to run that, you will get an error:

{
  "errors": [
    {
      "message": "Variable \"$trip\" of required type \"TripInput!\" was not provided.",
      "locations": [
        {
          "line": 1,
          "column": 21
        }
      ]
    }
  ]
}

The mutation is expecting some input, and we did not provide it.

So, in the “QUERY VARIABLES” textarea, enter in the following JSON:

{
  "trip": {
    "startTime": "2017-05-03",
    "title": "A test trip",
    "priority": "LOW",
    "duration": 86400
  }
}

Running the document now should give you a UUID back, though your value will (hopefully) differ from:

{
  "data": {
    "createTrip": {
      "id": "1924f3bf-75d8-4e5b-8d26-bf6c40e5425c"
    }
  }
}

And now, if you try querying the server, using a document like:

{
  allTrips {
    id
    title
    startTime
    priority
    duration
  }
}

you will see your newly-added trip:

{
  "data": {
    "allTrips": [
      {
        "id": "1924f3bf-75d8-4e5b-8d26-bf6c40e5425c",
        "title": "A test trip",
        "startTime": "2017-05-03",
        "priority": "LOW",
        "duration": 86400
      }
    ]
  }
}

GitHub

One of the most interesting firms to offer a public GraphQL API is GitHub, the popular project hosting service. GitHub has long had a REST-style Web service API, and in 2017 they added a GraphQL API.

Getting an Authentication Token

To work with GitHub’s GraphQL API, you first need to sign up for early-access program. This will require that you have a valid GitHub account and agree to a pre-release terms of service.

Then, you need to create a Web service personal access token. The GitHub documentation focuses on this as being for command-line use, though in truth it gets used elsewhere. Creating one of these tokens requires you to select “scopes” that describe what data you want to have access to — in production, you would create a token that had as little access as possible, to limit the amount of possible damage should that token become publicly accessible. GitHub’s documentation outlines a recommended set of scopes; those will be more than sufficient for your use with this book.

Accessing GitHub’s GraphiQL

At that point, you can visit GitHub’s copy of GraphiQL. When you do that, you will need to sign in with your GitHub account, in case you are using GraphiQL from a Web browser that is not already set up for use with GitHub.

And, with that, you can explore GitHub’s GraphQL support, much in the same way that you explored the GraphQL demonstration site that this book references:

GitHub GraphiQL
Figure 12: GitHub GraphiQL

GitHub API Documentation and Support

The GitHub Developer Web site has extensive documentation of their API.

GitHub also has a Discourse site category for the GraphQL API, should you encounter any specific challenges in using it.

And Now, Onwards and Upwards!

The preview of this section is out seeking fame and fortune as the Dread Pirate Roberts.