Everything you need to know about GraphQL

Written by geekyants | Published 2018/02/26
Tech Story Tags: graphql | apollo | react-native | react | backend

TLDRvia the TL;DR App

And a Chat App built using GraphCool!

#REST APIs are now #RestInPeace APIs | Long live #GraphQL

This was a tweet by Samer Buna. And I couldn’t agree with it more!

Ever since its initial release in 2015 by Facebook, GraphQL has seen an exponential increase in its community support. Today, thousands of companies use GraphQL in its production level apps.

Before getting into all of its sugary sweetness, let me beginning by defining GraphQL:

GraphQL is a data query language which presents itself as a better alternative to REST API and ad-hoc webservice architectures.

One of the great things about GraphQL is that it the client can define the structure of the data required, and the server will return data in exactly the same structure! In simple terms:

  • It lets the client specify exactly what data it needs.
  • It makes it easier to collect data from multiple sources(servers).
  • It uses a type system to describe data.

GraphQL servers are available for multiple languages, including JavaScript, Python, Ruby, Java, C#, Scala, Go, Elixir, Erlang, PHP, and Clojure.

The need for GraphQL — Limits of REST API

Say, you are creating a mobile app that has a list of movies, and under each movie, you want a list of main actors.

Seems easy enough. But when you try to load this data into your mobile app, you will find that things start to slow down.

And here I have only two movies, each with just two actors. In reality, my app may have to manage hundreds of movies, each definitely having more than two actors in it.

Solution

The solution to this problem is rather very simple. Instead of having multiple endpoints, have a single endpoint that can take in complex queries, and then change the data output into whatever structure the client requires.

And that is exactly what GraphQL does. It stays between the client and the data source (server), receives client requests, and fetches the necessary data according to the client’s instructions.

Here’s how the REST model would work in order to deliver the data to my app:

GraphQL on the other hand is like having a personal assistant, that simply asks what you want, and then gets it for you!

Benefits of GraphQL

  • Lesser Code
  • More declarative or elegant data retrieval
  • Avoids multiple REST calls
  • Backward compatible and version-free
  • Flexible
  • Better Performance
  • Powerful development tools
  • Can evolve with versions

What does GraphQL offer?

Fields

At its very base, GraphQL is all about asking for specific fields on objects. So if I wanted to know the name and abilities of a superhero, my query would be something like this:

GraphQL query and its response

As you can notice, the result has the exact same shape as the query. By using GraphQL, you will always get back what you expect because the server knows what fields the client is asking for.

In GraphQL, the fields can also refer to other objects. All you need to do is make a sub-selection of fields for that object. GraphQL queries can also traverse related objects and their fields, letting clients fetch lots of related data in one request, unlike REST API where you would have to make several roundtrips.

Arguments

Apart from letting us traverse objects and their fields, GraphQL also gives you the ability to pass arguments to fields.

Unlike REST, where you can only pass a single set of arguments, in GraphQL, every field and nested object can get its own set of arguments.

Aliases

Aliases are extremely helpful in querying for the same field with different arguments.

Mutations

While GraphQL queries help a client fetch data in any shape that they want, a client also needs some way to modify server-side data.

Any request has the potential to cause some kind of side-effects on the server. By it is usually suggested that one doesn’t use GET requests to modify data. Both REST and GraphQL are similar like that.

To write / modify data on the server side, GraphQL has provided us with a special field called Mutation.

Similar to queries, if a mutation field return an object type, you can ask for nested fields as well. This is very helpful in cases where you want to fetch the new state of an object after an update.

The createReview field will return the stars and commentary fields a review. This will be especially helpful when you need to change existing data.

Subscriptions

Subscriptions allow developers to introduce new levels of interactivity to their apps with near-realtime updates. By adding subscriptions, you can keep your app updated to the latest changes between different users.

The client specifies the data that they want to “subscribe” in a query like this:

When something is published to the subscribed channel, the server will run the GraphQL query specified in the subscription and sends a full new result to the client.

Unlike queries or mutations, subscriptions can deliver more than one result, so a long-lived connection is necessary. I suggest using a WebSocket connection.

How To Setup Apollo Client in your React/React Native Project

Setting up Apollo Client in your React/React Native project is fairly easy. All you need to do is write this code in your App.js file:

And voila! You have successfully set up Apollo Client in your React or React Native Project.

All you have to do is wrap your App component inside an ApolloProvider component.

Few more things to take care of. Make sure that you have added the following dependencies to your project.

  • Apollo-Client Preset
  • React-Apollo

By doing so, the queried data is now available in the props of the same component.

Build a ChatApp with GraphQL

Prameet Chakraborty, a software engineer at GeekyAnts built this awesome React Native ChatApp and used GraphQL for the backend.

Dependencies

GraphCool is the next big step in the evolution of GraphQL. What makes it even more “cool” is that it is open-source!

GraphCool Framework is a comprehensive collection of building blocks covering the entire spectrum of developing modern, data-centric GraphQL APIs including:

  • GraphQL database: A GraphQL database that allows you to query, mutate & stream data via the GraphQL CRUD API. It also contains a powerful database migration tool that lets you define and evolve your data model using GraphQL SDL.
  • Powerful permission system: Protects your GraphQL API with a powerful permission system based on rules you define in terms of simple GraphQL permission queries.
  • GraphQL subscription API: With the Graphcool Framework, realtime functionality (based on GraphQL subscriptions) comes for free. Your mutations automatically publish subscription events to the event gateway which forwards updates to all subscribed clients.

Apollo Client is an ultra-flexible, community driven GraphQL client. It is designed from the ground up to make it easy to build UI components that fetch data with GraphQL.

It is a community-driven effort to build a powerful, flexible and production ready GraphQL clients and supports various front-end frameworks such as React, Angular, and Vue.

NativeBase is an open source UI components library for React Native by GeekyAnts. NativeBase is one of the top choices for developers when it comes to UI components.

How it works

GraphQL provides an easier way to build a simple yet effiecient chat app. Here’s how Prameet’s chat app works:

  • A mutation is sent to the server in order to create a new user (Sign Up).

  • When a user tries to log in, a mutation containing the user’s credentials is sent to the server.

  • Once the user logs into the chat using their credentials, the app sends a query to the server to fetch all the users to the that have registered on the app.

  • The app also sends a query fetches all the messages and filters them based on the sender’s and the receiver’s id.

  • When a user sends a new message, the message is registered on to the server through a mutation.

  • All of these things are wrapped under a subscription.

Subscription to listen for any new created message

I am Rajat S, a Technical Content Writer at GeekyAnts. Aspiring Coder who has a long way to go. A Die-Hard DC Comics Fan who loves Marvel Movies. 😛 Follow me on Twitter to know about all the amazing things that are happening at GeekyAnts.

Thanks to Prameet Chakraborty for helping with this post and for helping me understand everything about GraphQL and the GraphCool Framework. Prameet is a software engineer at GeekyAnts. This post is inspired from his talk about GraphQL.

And thanks to you for reading this long post! Please do 👏 if you liked it.


Published by HackerNoon on 2018/02/26