📄 Table of Contents

  • what is graphQL?
  • Why and Why not graphQL?
  • Operations in graphQL (Queries & mutations)
  • How does GraphQL work

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ ✦ ✦ ✦ ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

Introduction

GraphQL was internally developed by Facebook in 2012. Facebook’s mobile apps have been powered by GraphQL since 2012. A GraphQL spec was open sourced in 2015 and is now available in many environments.

Relay is the javascript client for GraphQL that Facebook uses. It’s actually a software that adds many things on top of GraphQL such as query merging, pagination and deferred queries.

Bigwigs like Facebook, Twitter, Instagram use GraphQL in their tech stack for querying the data.

What ?

  • GraphQL stands for Graph Query Language.
  • GraphQL is an alternative to REST for developing APIs, not a replacement.
  • The main feature of GraphQL is to be able to send a query specifying only the information you need and get exactly that.
  • GraphQL is an open source server-side technology which was developed by Facebook to optimize RESTful API calls.
  • It is an execution engine and a data query language.
  • GraphQL allows making multiple resources request in a single query call, which saves a lot of time and bandwidth by reducing the number of network round trips to the server.
  • It also helps to save waterfall network requests, where you need to resolve dependent resources on previous requests.
  • GraphQL is faster than REST because as you can pick the fields you want to query, so the request will always be the smallest possible.

Why?

  • We can use GraphQL queries to fetch the required data to your components, instead of using the traditional REST API approach.
  • Another important feature of GraphQL is that multiple operations can be performed using a single endpoint and a single network request. This reduces the number of roundtrips and overall data transfer, which is very important on mobile devices and bad network situations.

Advantages compared to REST:

  • You define in the front end exactly what kind of data to use for each component.
  • Aggregation of data from multiple sources has been made quite easy by GraphQL.
  • Only the data needed for the components are sent over the network.
  • You don’t need to write many API endpoints, you only have one /graphql endpoint.
  • It has powerful developer tools that helps you visualize the data.

Disadvantages:

  • There is a learning curve.
  • Not as widely used as REST by existing public and private APIs.
  • GraphQL is famously bad at caching, mostly because the alternatives (REST and Falcor) make caching at all levels so easy and efficient. GraphQL is bad at sending anything other than text back and forth (such as file uploads) while REST APIs can do literally anything.

On the backend, you can create a GraphQL endpoint for your data with graphql.js together with a library for the web server you are using for example express-graphql. You can also use a SaaS for example graph.cool

On the frontend, you can use a library for connecting GraphQL to your react components. The two biggest ones right now are Appollo and Relay.

How does GraphQL actually work

The below diagram shows a Client-Server architecture. The web server is built on NodeJs and Express framework. A request is made to the Apollo GraphQL Server by ReactJS application (built using Apollo Client library) or GraphiQL browser application. The query will be parsed and validated against a schema defined in the server. If the request schema passes the validation, then the associated resolver functions will be executed. The resolver will contain code to fetch data from an API or a database.

Operations in GraphQL

There are two main types of operations in GraphQL, queries and mutations.

Queries are used to retrieve data while mutations are used for creating/updating/deleting data.

Examples

GraphQL mutation that adds a new user (and chooses which field to get a result on):

mutation CreateUser($name: String!){
createUser(name: $name) {
name
}
}

GraphQL Query

A GraphQL query is a string that is sent to the server to be interpreted, which then returns JSON back to the client in a specified format.

Some important features to be noted:

  • The first thing to be noted is that GraphQL queries mirror their response. This makes it easy to predict the shape of the data returned by the query as well as to write the query according to the data which we actually need.
  • Another important feature is its hierarchical nature. GraphQL naturally follows relationships between objects, where a RESTful service generally requires multiple round-trips.
  • It is a strongly typed language. Each level of GraphQL query corresponds to a particular type and each type describes a set of valuable fields.
  • The shape of the data which is returned is determined entirely by the client’s query, so servers become simpler and easy to generalize i.e. instead of defining the structure of responses on the server, the flexibility is given to the client.
  • GraphQL doesn’t require any specific technology or language. A GraphQL server can be built in any technology , just like a REST server.
Comparison between REST (left) and GraphQL (right)

How GraphQL can challenge the REST:

GraphQL challenges REST. The core idea is that the code that best knows what data is needed for a UI is not on the server but on the client. The UI component knows best what data it wants.

REST delivers all the data a UI might need about a resource and it’s upto the client to go look for the bits it actually needs to show. If that data is not in a resource it already has, the client needs to go off to the server and request more data.

What GraphQL does, UI gets exactly the data it needs.

Why REST is not enough:

When we want to build any view in our app that requires a tree of related resources e.g. a feed of shared photos with comments on them, you have to make multiple requests which can be very slow especially when those requests can’t be made in parallel. The code to perform these fetches can also become quite complex. You end up creating custom end points for specific needs of your app, with lot of backend code.

A GraphQL backend has a schema that defines which fields and calls are available for each type of data. This means adding new models or fields becomes a simple task of adding or modifying types in the schema. When a field has been added in the schema it can be queried. A frontend developer can then go and make a change in just the component that actually uses the data and it works. GraphQL makes it possible to build a backend and integrate it with the frontend with much less custom plumbing than before and to make fast changes with less fear of breaking things.

Reference:https://medium.com/better-programming/convert-traditional-graphql-query-to-hooks-9fc50969914

At its simplest, GraphQL is about asking for specific fields on objects. Let’s start by looking at a very simple query.

GraphQL query that gets the list of users:

{
hero {
name
}
}

The result we get when we run it.

You can see that the query has exactly the same shape as the result. This is essential to GraphQL, because you always get back what you expect, and the server knows exactly which fields the client is asking for.

Real-world query example

Let’s look at a real-time example for making a GraphQL query inside a React class component.

npm install react-apollo

This package exports the Query for us.

npm install graphql-tag

A JavaScript template literal tag that parses GraphQL query strings into the standard GraphQL AST.

Then, import the Query from the installed package and use it as shown in the example below.

If you notice, we also have two more states, error and loading, in addition to the actual data.

Loading state

When this component mounts, the GraphQL query sent in the background may not have been completed. But we need to handle that temporary state of no data and hence, we return some useful text during the loading state.

In this loading state, typically you can do fancy things like displaying a loading spinner.

Error state

Now, the query could also end up in an error state due to various reasons. Sometimes the GraphQL query could be wrong or the server isn’t responding.

Whatever may be the reason, the user-facing UI should show something to convey that an error has occurred. In this error state, typically you can send these error messages to third-party services to track what went wrong.

How to Convert a Traditional GraphQL Query to React Hooks

Now, if you are to change the traditional query to Hooks, you have to do the following:

npm install @apollo/react-hooks

It will provide you with the useQuery Hook, import this Hook and use it as shown in the below example for your functional React component.

Example 1:

Example 2:

First, we’ll create a GraphQL query named GET_DOGS. Remember to wrap query strings in the gql function to parse them into query documents:

demonstration of a traditional query for a React class component

Next, we’ll create a component named Dogs. Inside it, we’ll pass our GET_DOGS query to the useQuery Hook:

example is of a React functional component using Hooks.

As our query executes and the values of loading, error, and data change, the Dogs component can intelligently render different UI elements according to the query’s state:

  • As long as loading is true (indicating the query is still in flight), the component presents a Loading... notice.
  • When loading is false and there is no error, the query has completed. The component renders a dropdown menu that’s populated with the list of dog breeds returned by the server.

Real-world mutation example

Now that we know how to query for data, let’s look at how to create mutations.

Now we will see how to call the mutation we created above to save a record.

Conclusion

Hooks are a powerful addition to React. Also, React Hooks is a powerful library to use Hooks with GraphQL in your React app. I would recommend getting your hands dirty with Hooks now as you already have the foundation.

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store