Alexito's World

A world of coding 💻, by Alejandro Martinez

A quick API layer with GraphQL

Facebook has brought to the open source world a bunch of amazing technologies, React being one of the more widespread ones. It is really interesting how old ways of doing UIs like the immediate GUI mode has come back with a more functional and descriptive twist. But for me one of the key and most amazing technologies is GraphQL.

I've been really interested on GraphQL since they first talked about it in a talk, when it wasn't even open source. Since then it has been released as a spec and with an example implementation in Javascript. From there tons of people has ported this technology to its preferred language. Now I'm excited to so see how is being use more and more, improving the development workflow of client side developers.

It's been a while since I wanted to do something with it but time is always a hard thing to manage, specially with so many interesting things to learn! My initial idea was to use it for my next personal project that I wanted to tackle, but I needed to have a API server for that, and it will take a while.

A couple of weeks ago, one evening, I realised that I already have an API server that I'm familiarised with, the one with which I work everyday. So without thinking it twice I pulled the Javascript implementation of GraphQL and started building a GraphQL layer for my J.O.B. API. It was just to see what is involved in making a GraphQL server and it uses private APIs so it's not open source or even used! But it was a really interesting experiment to see how easy it is to create this API layers.

GraphQL is not based on different endpoints for each resource, instead it exposes Query objects to which you can ask for data starting for the root level and specifying all the subnodes that you want until reaching the leaves. The query is usually specified in a JSON like structure.

  {
   users {
     id,
     name,
   }
 }

In my case this returns:

  {
   "data": {
     "users": [
       {
         "id": "1",
         "name": "Dan"
       },
       {
         "id": "2",
         "name": "Marie"
       },
       {
         "id": "3",
         "name": "Jessie"
       }
     ]
   }
 }

This is the first aspect of GraphQL that when you stop for a second you realise how amazing it is. It exposes the query scheme to the clients. This means that the API is self documented, you can explore an API dynamically! This is one of the biggest pitches to introduce people to this tech and is usually done in form of showing of GraphiQL, an amazing API explorer.

GraphiQL example

See how you can write your queries, receive suggestions of the available fields with type information, see the response of that query and even explore the documentation of the exposed types. This feels like an impossible thing if you are used to deal with poorly documented APIs.

The GraphQL engine is in charge of decomposing the querys using your provided scheme, your code, and using it to resolve certain fields. When you start writing some GraphQL code you realise how this simplicity is really powerful.

  var QueryType = new graphql.GraphQLObjectType({
     name: 'Query',
     fields: {
         user: {
             type: UserType,
             args: {
                 id: { type: graphql.GraphQLString }
             },
             resolve: function (_, args) {
                 return data[args.id];
             }
         },

A part from the obvious definition of the fields and its types, the resolve function is the interesting bit here. There you can write any code you want that returns back the field (or a promise). You can just read data from an in memory structure (like the example), load it from a file, access a database or, the most interesting, make any HTTP request to another server.

This is what I've used to interact with the API.

  resolve: function () {
        return
         fetch('<https://...')>
            .then(function (res) {
                return res.json();
            }).then(function (json) {
                return json['body']
            });
    }

One of the other important examples to consider is that you can make more than one request in the resolve function. For example if your API embeds relationships just with their IDs

  {
  ...
  friends: ["1", "2", "56"]
 }

you could iterate over the friends array and resolve them all making different request, everything on the server.

When all of the resolves are done the GraphQL engine merges back the fields that have been requested and returns that in one go to the client. This allows the clients to just ask for what they want, nothing more nothing less. Not wasted resources. Furthermore, because there is no separate endpoints or resources, you could ask for different types in the same query which is really useful.

Easy has that. Obviously in a real world project there are more aspects to consider like error handling, pagination, filters, etc. But it's amazing how easy is to start and have something functional in one evening.

The sad part is that right now is not easy to use in iOS, unless you buy into React Native. I hope that soon we start seeing people and companies to invest in building native GraphQL engines.

UPDATE: I just saw this post by Artsy! GraphQL for iOS Developers I recommend you to take a read to understand how they are using it in their mobile apps.

If you liked this article please consider supporting me