GraphQL: does that word ring a bell? Hint: you use it every day on Facebook. “The Social Network” has been using GraphQL for its platform since 2012. And guess what: it is now open source. Fantastic, isn’t it?

Wait but what is GraphQL?

By definition, “GraphQL is a query language for your API, and a server-side runtime for executing queries by using a type system you define for your data. GraphQL isn’t tied to any specific database or storage engine and is instead backed by your existing code and data.” (Source: GraphQL.org)

Since it became open source in 2015, GraphQL has been enjoying a growing activity. It is used by teams of all sizes in many different environments and languages to power mobile apps, websites, and APIs. Famous companies such as Twitter, Yelp, Pinterest, and Coursera rely on GraphQL for their platforms.

At this point, you may have some questions in your mind:

• What are the benefits of GraphQL?
• Why do so many companies use it?
• Why not using REST? Is it any better?

At the end of this article, you will have a great overview of everything you need to know about GraphQL. How about starting now?

GRAPHQL PREVAILS OVER REST

While GraphQL has a clean layer of abstraction between servers and clients, REST only has an ad-hoc approach. Actually, GraphQL solves many issues of REST. Here are its four main assets:

GRAPHQL HAS FEWER ROUNDTRIPS THAN REST

One of the major issues of REST is that it multiplies round-trips to let you call several related functions. Each API request to pull a resource is a separate HTTP request-response cycle. Fetching complicated data requires multiple round-trips between the client and server to render even a single view. For mobile applications in variable network conditions, this is highly undesirable.

On the contrary, GraphQL enables you to call several related functions without multiple round-trips. To make that happen, GraphQL unifies data and create packages, instead of letting multiple endpoints exist.

This way to package data has two benefits:

• more efficient data delivery
• fewer resources required for roundtrip calls.

If you are a more visual person, here is the illustration:

rest as multiple roundrips whereas graphql use only one roundtrip

GRAPHQL HAS A MORE ELABORATE TYPING SYSTEM THAN REST

GraphQL is endowed with more specific and powerful queries than REST. The latter suffers from not having a very sophisticated typing system. You often end up with variants of typing settings to fit REST standard calls — even with good implementations.

GraphQL solves this problem with a typing system which allows you to describe the schema of data that is available on the server.

Wait, did you say “schema”?

Schema is a central point of GraphQL. Schema defines a namespace for type definitions. For each schema definition, there is a root query. A root query is a GraphQL object definition which exposes all top-level fields to be requested by the user.

Later, these schema definitions can be used to:

• generate documentation, introspection queries
• execute and validate incoming GraphQL queries and mutations.

Friendly tip: you need to understand the difference between Input and Output type definitions. Trust me, it will save you some precious time in the future.

The distinction is important because not all type definitions are both valid inputs and outputs.

• Output types define valid types that can be used as GraphQL query responses. They include: objects, interfaces, unions, enums, scalars, lists, nullables

• Input types define types that can be used as valid values included in GraphQL query itself or as a set of attached variables. They include input objects, enums, scalars, lists, nullables.

So output types are used to validate and format responses which come from resolvers functions, and input types to validate and format input data from client.

GRAPHQL HAS A BALANCED RELATIONSHIP BETWEEN CLIENT AND SERVER

REST uses thin client. Because of this, there is a heavier load of data processing to the server. As a consequence, even if the relationship between client and server is well-defined, it is unbalanced. As devices have still more processing power and ability, the unbalanced relationship has to be rethought.

This rethinking has been done by GraphQL. The latter balances the data processing almost equally between the client and the server. This has been made possible by offloading specification of expected data format to the client and structuring data around that call on the server side. A balanced relationship has clearly a positive effect on the performance of GraphQL-based applications, as fewer server resources are used in query processing.

GRAPHQL IS NATIVELY DISCOVERABLE

With REST, there is no native discoverability since it requires specific implementations. REST has no native documenting functionality and requires to use external solutions such as Swagger or HATEOS. But even if you use those external solutions, it still lacks discoverability: the server response has constraint structures, HTTP has restrictive mechanisms, etc. So you can add a functionality but bear in mind that it will accentuate the complexity of REST.

Contrary to REST, GraphQL is natively discoverable since it is based on relational data and on self-describing. Self-describing is essential for compatibility with third-party applications as well as for the API introduction to users and developers.

WHY START USING GRAPHQL TO BUILD AN API

CLIENT-SIDE DEVELOPER: YOU OPTIMIZE YOUR TIME

The client-side developer can add features to the app without touching any part of the app, including the server code. You just have to change your GraphQL query and… that’s all folks! Gone are the days when you needed to change the REST endpoint structure to fetch different data.

With GraphQL, the server architecture is simplified and the access to data is easier. A client-side developer can write a query to a GraphQL server and fetch data, just like that. You just have to change the GraphQL query and… you get the data you need. Again, gone are the days when you needed to ask the server-side developer to create a custom data endpoint.

SERVER-SIDE DEVELOPER: WELL, YOU OPTIMIZE YOUR TIME TOO!

Learning to use GraphQL will only take you a couple of hours. However, it will save you some precious time. There are four main reasons:

• You will have clean API between backends and frontends
• You will have great tooling for your API
• You won’t spend more time writing API documentation
• You will have fewer meetings with client-side developers

HOW TO BUILD AN API WITH GRAPHQL?

If you want to build efficiently an API with GraphQL, you have to keep in mind those rules.

STICK TO ONE QUERY PER RESOLVER

By sticking to one query per resolver, you won’t spend more time writing and rewriting code every time the API changes.

CHOOSE THE RIGHT ABSTRACTIONS

With GraphQL, there are four layers of abstractions. Here they are, starting from the top:

• Schema
• Resolvers
• Models
• Connectors

The first layer of abstraction is produced by GraphQL schema, which hides the details of the backend architecture from the front end. At this layer, you choose which types and fields will create each application.

The schema itself is constrained, so you have to use resolvers to get the flexibility you need in GraphQL. This flexibility is essential to let a schema map to any number of backends.

The second layer of abstraction concerns resolvers. They define how the data for a field in a query is actually fetched.

What are steps between layers

Source: Apollo

Then, there are two more abstractions in GraphQL which help you structure your code: model and connectors. Models and connectors are not abstractions that are built into GraphQL. But they emerge as a natural way to structure code in a GraphQL server.

The model layer is here to expose a generic interface to resolvers. The model layer uses the connectors layer to get access to whatever database, for example via a possible Object Relational Mapping (ORM).

The connectors layer exposes functions to manipulate data used by the model layer. These functions interfaces depend upon what database or ORM is chosen. It also takes care of setting up the different connections to databases. They only need to be implemented once for each backend and can be reused in many apps.

CONCLUSION

It takes only a few hours to learn GraphQL and 5 minutes to learn how to use your API with it. Since GraphQL is a specification, you will find many libraries to help you implement GraphQL in many different languages such as JavaScript, Java, PHP, Python, Go, etc.

Moreover, there is a friendly community of developers — both users and contributors of GraphQL — who will support you. Bonus: you can start here:

Useful accounts to follow: @GraphQL, @graphqlweekly, @graphqlnews, @GraphQLStackOverflow, @apollographql, @graphcool, @ScapholdDotIO, @FdMstri
Monthly podcast: Graphqlradio
Slack Communities: ApolloSlack, ReindexSlack, GraphcoolSlack, Scaphold.ioSlack
… and my articles on Medium

So I definitely invite you to take some time to learn about GraphQL. How about using it in your next project? The next step is to try to convince your colleagues or your boss to start adopting it. And I guarantee you that you won’t regret it!

Thanks for your time, we hope you enjoy the read!

Join our vibrant community of freelance developers and data experts by clicking here : https://comet.co/en/freelancers

Follow us on LinkedIn - Twitter - Facebook - Medium

    Share: