I think that GraphQL is not that different from REST but dramatically improves the developer experience of building and consuming APIs.


If you are like me when you come across a new technology there is one small moment of frustration but after you start reading the documentation and examples, you get more and more interested in it and want to start trying it even before you finished skimming the docs.

This is the case with me and GraphQL... once again.

In my previous job I had some communication with one of the ProductHunt iOS app's developers. He told me about GraphQL and that they're using it to communicate with the back-end as well as how cool it was! Back then I didn't check it out but a few days ago I had an interview for another mobile dev position and they gave me the task to research GraphQL and to find out what is the benefits of using it over REST.

So, in this article I will share with you what I found out and my thoughts about it. Sorry, I'm already biased... GraphQL rocks!

Background

Representational state transfer (REST)

The first inception of this architectural style was in 2000s when Roy Fielding defined it in his PhD dissertation "Architectural Styles and the Design of Network-based Software Architectures" at UC Irvine.

REST is basically a way of accessing remote web resources defined in unique URLs (Uniform Resource Locator).

Web resource, or simply resource, is any thing like file or page, that cam be accessed via unique URL.

In this example, you can see that we're making a GET request to endpoint /api/user/1 to get the user with id = 1.

So, lets dissect this request:

  1. What is this GET thing in the first line?!
    This is the HTTP method we use to access the resource. There're several HTTP methods that tell the server what is our intent - GET, POST, PUT, DELETE...
  2. What is the following text after GET?
    This is the endpoint URL where we specify that we want to access the users and get exactly the user with id = 1
  3. What is this thing in the curly braces?
    This the payload that the server returns if the request is successful. In our case it is, so we receive the expected user object.

What is the problem? Do we need another way of consuming APIs?

Don't get me wrong, REST is nice way of working with APIs! However, as everything it has its own pluses and minuses.

Let's review what are some of the main problems when consuming REST APIs from client mobile or web apps:

  1. The biggest problem is the nature of multiple endpoints making the client to do multiple request-trips to access their data.
  2. Clients don't have control over what the API will return as response.
  3. Versioning - if you want to support multiple versions, that usually means adding new endpoints.

These are some of the most annoying problems. So, let's see if GraphQL could address them and improve the way of how the clients consume APIs.

GraphQL

GraphQL is all about data communication and how to improve the way of how the clients are accessing the resources provided by APIs.

QL stands for Query Language. Yes, you're right! Just as the first thought you get in your head - SQL.
However, Graph there's nothing to do with graph databases or anything else.

GraphQL is developed by Facebook and introduced in 2011. Maybe you're worried that Facebook is involved in it but don't! GraphQL is just a specification, not a library. There're numerous libraries developed by the open-source community for almost all of the languages out there.

Let's see an example query and response before continue to the GraphQL building blocks and how it addresses the previously mentioned REST problems.

What you can easily see at first glance is that the response on the right is:
1. JSON
2. Exactly the same structure like the query on the left

Isn't that cool? What do you think? 😎

Let's see how GraphQL addresses previously mentioned REST problems

  1. Get many resources in a single request
    When you make a query (request) you call just a single endpoint and passing the query object. That is huge! This opens the possibility to fetch multiple resources at once!
    For example, you can fetch the user and his friends with a single request instead of one for the user and another requests for each of the user's friends.
  2. Ask for what you need, get exactly that
    When calling REST API, you don't have control over the response data. In GraphQL, you can select only the fields what are most meaningful for you.
    For example, you can request only the firstName and lastName of the user.
    Apps using GraphQL can be quick even on slow mobile network connections.
  3. No need for versioning
    With GraphQL there's no need for versioning when you have to add new endpoints. You just add new queries and mutations and expose them to the clients. That's it!
  4. Describe what is possible with a type system
    GraphQL APIs are organized in terms of types and fields, not endpoints. GraphQL uses types to ensure Apps only ask for what’s possible and provide clear and helpful errors.

GraphQL Building Blocks

When building a GraphQL API you're using Object Types and Fields, Queries and Mutations and Schemas.

Object Types and Fields

GraphQL is typed language so we have to define our types which are basically the representation of objects we want to fetch from our service. Here is a basic example of a User type:

Definition in GraphQL schema language. Review the GraphQL specific language's library documentation.

I'm sure that most of you understand what is happening here, but lets review it:

  • User is GraphQL Object Type, meaning it's a type with some fields.
  • firstName, lastName and email are fields on the User type.
  • String is one of the build-in scalar types - these are types that resolve to single scalar object, and can't have sub-selections in the query.
  • ! in String! means that the field is non-nullable, meaning that the GraphQL service promises to always give you a value when you query this type.

The Query and Mutation Types

Most types you will define in your schema will be just normal object types. However, there are two special types which represent intended actions:

  1. Query - executes a fetch action. Used when you want to obtain something from the API.
  2. Mutation - executes create/update action. Used when you want to add new data or update existing one.

Here is an example of how to use these types:

Schema

The last part is to bundle all of the query and mutation types into a GraphQL Schema. Basically, the Schema is the object exposing the API to the client who will consume it.

Lets see what it is like:

Similarities and Differences between REST and GraphQL

Similarities

πŸ‘‰πŸ» Both can return JSON data in the response
πŸ‘‰πŸ» Both can be fetched via HTTP request with a URL
πŸ‘‰πŸ» Both have the idea of a resource and can specify IDs for those resources
πŸ‘‰πŸ» The list of endpoints in a REST API is similar to the list of fields on the Query and Mutation types in GraphQL. They're both entry points to the data.
πŸ‘‰πŸ» Endpoints in REST and fields in GraphQL both end up calling functions on the server

Differences

πŸ‘‰πŸ» In REST, the response payload is determined by the server. In GraphQL, the server declares what resources are available and the client selects what he needs.
πŸ‘‰πŸ» In REST, the endpoint you call is the identity of that object. In GraphQL, the identity is separated from how you obtain it.
πŸ‘‰πŸ» In REST to tell the server about your intended action, you have to specify a HTTP Method in the request - GET, POST, PUT... In GraphQL you use either query or mutation keyword.
πŸ‘‰πŸ» In REST, there's no first-class concept of a nested URL. In GraphQL you can have arguments in any field in the query.
πŸ‘‰πŸ»In REST, you have to call multiple endpoints to fetch related resources. In GraphQL you can obtain related resources in a single query.
πŸ‘‰πŸ» In REST, you have to construct the shape of the response. In GraphQL, the GraphQL execution library builds it up for you to match the shape of the request.
πŸ‘‰πŸ» In REST, each request usually calls exactly one route handler function. In GraphQL, one query could call many resolvers to construct a nested response with multiple resources.

Conclusion

As you can see, they're not that different but GraphQL has some differences that make a huge impact of how the clients consume APIs. It focuses more over the clients instead of the servers. GraphQL is much more easier to be worked with as it returns only what you need in a single request. Also, you can use it alongside your existing REST API!

So, what do you think?
Will you try it in your existing or new projects?

Share your thoughts in the comment box below πŸ‘‡πŸ»