Blogs | Srijan

GraphQL - Future of API Management

Written by Manisha Gupta | May 14, 2020 7:00:00 AM

Of late, GraphQL has come out as an alternative to REST APIs—but as with anything else, it has its pros and cons. This blog will highlight the major features of GraphQL and the advantages that it has over REST.

GraphQL - why is it popular?

GraphQL is a revolutionary way to think about APIs. The “graph” stands for crawling across API’s by using fields and subfields, while QL stands for the query language.

"GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API"

It is a query language for APIs that provides a complete description of the information in your API and gives clients the facility to articulate exactly what requirements they have, thereby making it easier to evolve APIs over time and enabling powerful developer tools.

Why GraphQL if there’s already REST?

There are two main reasons why companies like Facebook, Netflix, and Coursera started developing alternatives to REST-

  1. Within the early 2010, there was a boom in mobile usage which led to some issues with low-powered devices and sloppy networks. REST isn't optimal to cope with those problems.
  2. As mobile usage increased, so did the number of various front-end frameworks and platforms that run client applications. Given REST's inflexibility, it was difficult to develop one API that would fit the necessities of every client.

Going further, we even realized that the main reason why another solution was identified was that the majority of the information utilized in modern web and mobile applications has a graph shape. Consequently, Facebook started developing GraphQL in 2012 in its native mobile apps

The first time it publicly spoke about GraphQL was at React.js Conference 2015 and shortly after that, it announced its plans to open source it.  Because Facebook always wanted to talk about GraphQL within the context of React, it took ages for non-React developers to understand that GraphQL was by no means a technology that was limited to usage with React.

Why Drop REST? 

See how GraphQL is beneficial than Rest-

1.   Data Fetching

REST is an API design architecture that ensures web services implementation. RESTful web services are one way that allows computer systems over the internet to access and manipulate the textual representations of web resources using a predefined set of stateless operations (including GET, POST, PUT, and DELETE). Each resource is identified by a URL, and we retrieve that resource by sending a GET request to its URL. We’ll likely get a JSON response since that’s what most APIs are using nowadays.

Source: howtographql

 

With GraphQL, we only get one endpoint, and therewith, we will get the maximum amount of data as we would like during a single request. Primarily, GraphQL wraps all of our queries, mutations, and subscriptions in one endpoint and makes it available to us. It improves our development cycle because we don’t have to make two requests to induce data from two different resources. 

Also, imagine that we’re building an enormous application, we won’t get lots of endpoints and plenty of code like REST. We'll get one endpoint, and therewith endpoint, we will make as many requests as we would like.

Source: howtographql

 

2.   Network Requests

A closer look at the instance above within the REST implementation; notice we've got three different endpoints to fetch the info for our scenario that we are going to need - to make three different requests to the server.

On the other hand, the GraphQL implementation requires us to make one request to the server. 

GraphQL reduces network requests by allowing us to fetch or retrieve all the info we want in a very single query.

3.   Over/Under Fetching

It is easy to fetch the information with REST because each endpoint during a REST API includes a fixed organization which it is meant to return whenever it's hit. So, most of the time, we just move with the information that we want and find ourselves ignoring the remainder. 

Also, REST makes it easy to fetch data hence making us perform additional requests to other endpoints to fetch associated data.

With GraphQL that's not the case. Because GraphQL can be a declarative data fetching specification and a query language, thus, we only fetch what we want from the server by constructing our query to only include what we want.

4.   Error Handling

Error handling in REST is pretty straightforward. We simply check the HTTP headers to urge the status of a response. Looking at the HTTP status code ( 404, 503, 500, etc) we get, we can easily tell what the error is and the solution to resolve it.

GraphQL on the opposite hand, when operated over HTTP will always get a 200 OK response status. When a blunder occurs while processing GraphQL queries, the whole error message is distributed to the client with the response.

5.   Caching

Since HTTP already implements caching, and REST is implemented using HTTP, we can use HTTP caching to avoid fetching resources.

GraphQL has no caching mechanism, hence clients are taking care of caching on their end.

6.   Version control

Often when consuming third-party REST APIs, we see stuff like v1, v2, v3, etc. which simply indicate the version of the REST API we are using. This ends up in code redundancy and fewer maintainable code.

In the case of GraphQL, there's no need for versioning as we can easily add new fields and kinds to our GraphQL API without impacting existing queries. Also, we can easily mark fields as deprecated and therefore, the fields will be excluded from the response obtained from the server.

GraphQL Libraries

Here are some of the most effective GraphQL tools and libraries around, from client to server-side libraries and useful integrations.

a.  Clients

  • Relay- Relay is a JavaScript framework for building data-driven React applications Powerful GraphQL client developed by Facebook, heavily optimized for performance.

 

Code Example-

import React from "react"

import { createFragmentContainer, graphql, QueryRenderer } from "react-relay"

import environment from "./lib/createRelayEnvironment"

import ArtistHeader from "./ArtistHeader" // Below




// You can usually use one query renderer per page

// and it represents the root of a query

export default function ArtistRenderer({artistID}) {

  return (

    <QueryRenderer

      environment={environment}

      query={graphql`

        query QueryRenderersArtistQuery($artistID: String!) {

          # The root field for the query

          artist(id: $artistID) {

            # A reference to your fragment container

            ...ArtistHeader_artist

          }

        }

      `}

      variables=

      render={({error, props}) => {

        if (error) {

          return <div>{error.message}</div>;

        } else if (props) {

          return <Artist artist={props.artist} />;

        }

        return <div>Loading</div>;

      }}

    />

  );

}
  • Apollo Client: Community-driven effort to create a robust, flexible and production ready GraphQL client for all major development platforms. It supports various frontend frameworks like React, Angular, and Vue and platforms like iOS and Android.

Code Example Installation- 

npm install apollo-boost graphql react-apollo
 

Open src/index.js and replace the contents with the following:

import React from 'react'

import ReactDOM from 'react-dom'

import './styles/index.css'

import App from './components/App'

import * as serviceWorker from './serviceWorker';




// 1

import { ApolloProvider } from 'react-apollo'

import { ApolloClient } from 'apollo-client'

import { createHttpLink } from 'apollo-link-http'

import { InMemoryCache } from 'apollo-cache-in memory'




// 2

const httpLink = createHttpLink({

  uri: 'http://localhost:4000'

})




// 3

const client = new ApolloClient({

  link: httpLink,

  cache: new InMemoryCache()

})




// 4

ReactDOM.render(

  <ApolloProvider client={client}>

    <App />

  </ApolloProvider>,

  document.getElementById('root')

)

serviceWorker.unregister();

b.  Server

  • GraphQL.js: It is the reference implementation of the GraphQL specification, designed for running GraphQL in a Node.js environment.
var { graphql, buildSchema } = require('graphql');




// Construct a schema, using GraphQL schema language

var schema = buildSchema(`

  type Query {

    hello: String

  }

`);




// The root provides a resolver function for each API endpoint

var root = {

  hello: () => {

    return 'Hello world!';

  },

};




// Run the GraphQL query '{ hello }' and print out the response

graphql(schema, '{ hello }', root).then((response) => {

  console.log(response);

});
  • Graphql-tools - a package that enables you to build a production-ready GraphQL.js schema using the GraphQL schema language, rather than using the GraphQL.js type constructors directly. This allows additional support for resolvers, unions, interfaces, custom scalars, modularizing your schema, and more.

Sample Schema:

const typeDefs = `

  type Author {

    id: Int!

    firstName: String

    lastName: String

    """

    the list of Posts by this author

    """

    posts: [Post]

  }




  type Post {

    id: Int!

    title: String

    author: Author

    votes: Int

  }




  # the schema allows the following query:

  type Query {

    posts: [Post]

    author(id: Int!): Author

  }




  # this schema allows the following mutation:

  type Mutation {

    upvotePost (

      postId: Int!

    ): Post

  }

`;

Sample Resolver:

const resolvers = { Query: { posts: () => posts, author: (_, { id }) => find(authors, { id }), }, Mutation: { upvotePost: (_, { postId }) => { const post = find(posts, { id: postId }); if (!post) { throw new Error(`Couldn't find post with id ${postId}`); } post.votes += 1; return post; }, }, Author: { posts: author => filter(posts, { authorId: author.id }), }, Post: { author: post => find(authors, { id: post.authorId }), }, };

 

A production-ready Node.js GraphQL server library that supports Express, Connect, Hapi, Koa, and other popular Node HTTP servers, with built-in features like persisted queries, batching, and more. Apollo Server works with any GraphQL client, like Apollo, Relay, and more.

GraphQL Tools

Following are the prominent GraphQL tools-

An interactive in-browser IDE for exploring GraphQL.

  • Altair GraphQL Client

Altair has a variety of useful features which includes linting of query, showing schema docs, providing autocomplete functionality, the flexibility to set headers, etc.

  • Postman

Send GraphQL queries in the request body as POST requests, support GraphQL variables, and create APIs in Postman with GraphQL schema type, etc.

Summing up

At Srijan, we have a learning curve for GraphQL which is not as established as REST APIs but still, it is worthwhile.
When focusing on automation, our life as developers become much easier provided, we receive only the information that we want and nothing else.
As a bonus, the performance of our automation processes increases at scale, ensuring our big wins.