See all articles
GraphQL Part #1 - Explaining GraphQL and How it Differs from REST and SOAP APIsExplaining GraphQL and How it Differs from REST and SOAP APIs

GraphQL Part #1 - Explaining GraphQL and How it Differs from REST and SOAP APIs

There’s a new kid in town… GraphQL presents a new way to build APIs, that builds on solid concepts of the past and comes to grips with the inefficiencies RESTful architectures. Check out the differences, similarities, and comparison code snippets in this article.

GraphQL is a new approach to building APIs. REST style APIs have reigned supreme for some time now, but GraphQL is helping us to redefine the way that APIs communicate. While many have touted GraphQL as the ushering in of a new era when it comes to defining APIs, as with all technologies, there are specific cases where one is likely to do a better job than the other. However, as GraphQL gains traction, developers are starting to prefer using this new communications protocol and suite.

What’s the most basic difference between RESTful APIs and GraphQL? Well, as opposed to a REST API, where each resource can be identified by the URL and fetched by sending a GET request to that specific URL, API development with GraphQL requires a schema to define the resources it is going to operate on. In order to access or modify these resources, you need to create a `Query` or `Mutation` type that will be sent to the server.

GraphQL goes way beyond the principles of a RESTful application. It is more than just a specification - it’s also a query language with tools that with help you to work over a single HTTP endpoint to query and mutate the data. As a more complete toolset, it can help developers quickly define comms - and more efficiently in many cases, too.

For more knowledge, see our whole GraphQL Development Series:

  1. GraphQL Part #1 - Explaining GraphQL and How it Differs from REST and SOAP APIs [you are reading this article now]
  2. GraphQL Part #2 - Creating an API with Node.js Using GraphQL
  3. GraphQL Part #3 - Creating a GraphQL Client with the Vue.js Framework
  4. GraphQL Part #4 - Build GraphQL API with Ruby on Rails

A brief history of API architectures - Or an overhead GraphQL REST SOAP comparison

Before the RESTful style of architecture became king of the game, the world of constructing APIs was dominated by SOAP. It had a completely different approach, based on the RPC protocol, with XML as the only supported message format. The RPC (Remote Procedure Call) protocol allows clients to request a service from another resource on the network without knowing about the network, as if the request was done locally.

Compared to REST, SOAP had a large data payload (the SOAP “envelopes”) and web services were expensive to maintain. SOAP APIs had a complex and fragile communication interface, that had to be precisely followed on the client side - as even a small server-side change could result in a break in communications for API consumers. In order to make SOAP work, the list of available operations and strict definition of supported data types was enclosed into a document named WSDL.

GraphQL is somewhat similar in overarching theory to concepts that were proposed by SOAP. It combines the good parts of the heavy, old-school SOAP API protocol with the freshness of the REST architecture. It is strongly-typed and uses metadata, with a single endpoint URL - just like SOAP did - but at the same time it communicates using a lightweight JSON payload and operates on resources (instead of RPC).

Considering all this, it is safe to say that GraphQL is a natural step forward in the evolution of API architectures - and it took the right lessons from the past experience of web developers.

API developers using GraphQL include companies likes Facebook, GitHub, Pinterest and Shopify -all betting on GraphQL to build their APIs.

Let’s take a look at the GraphQL and REST APIs similarities and differences.

Similarities between a GraphQL and RESTful API

  • Both have resources which can be identified by their IDs
  • Both can exchange data using the `JSON` format
  • Both can fetch data with the `GET` request

Differences between a GraphQL and RESTful API

  • An endpoint in a RESTful API maps to the identity of the object you are calling. In GraphQL, an object’s identity is separated from the manner in which it is fetched
  • In a RESTful API, it is the server’s responsibility to define the shape and size of the response. In GraphQL, a server declares what is available and the client asks for what it needs

Pros and cons of a GraphQL API

GraphQL Pros

  • Flexibility - a client asks exactly what data is needed and the server returns it
  • Easier versioning - data is defined by the query, not by the server
  • Reduction in data volume - the server sends only what is requested by the client
  • Aggregated queries - allowing us to retrieve resources and their subresources in a single API call
  • Community and ecosystem of libraries

GraphQL Cons

  • Less intuitive error handling - because GraphQL is protocol agnostic, every response is going to return a `200` response code - with the actual problem described inside a response’s body. This basically means you can no longer rely on status codes for handling errors.
  • Caching difficulty - because the shape of a REST API response is known ahead of time, you can easily cache it on the backend or frontend (for offline use). In GraphQL, each request can require a different shaped block of data, which makes caching harder.
  • Lack of consistency in operations - with REST, there is a standard worked out over the years so that if you call `GET /users/:id`, then you’ll probably be able to delete the same user with `DELETE /users/:id`. With GraphQL, people can use different names for similar actions i.e. `createUser` vs `userCreate`.
  • Server side implementation concerns - since queries are defined by the client in GraphQL, you need to ensure that your service side is safe from things like resource exhaustion attacks (when clients send a very complex query e.g. for deep nested relationships such as user → followers → followers) or N+1 queries (when resolving each of the query fields).
  • Lack of versioning - GraphQL does not support versioning. As an alternative, it allows us to define certain fields as deprecated. However, if an application is already in production, you can easily miss this type of information, which can result in errors once fields get changed.

REST vs GraphQL examples

We already covered some of the differences between REST and GraphQL APIs from a theoretical point of view, so let’s compare them now with some simple examples.

Let’s imagine you have an API which returns the top trending TV series.

REST API example

REST Resources

For resource definition, we will use Ember Data - which with the JSON API adapter is one of the most complete `JSON API` implementations based on RESTful architecture.

  • series:
var Series = Model.extend({
    name: attr('String'),
    producer: belongsTo('Producer')
  })
  • producer:
var Producer = Model.extend({
    name: attr('String')
  })

REST Request

Here is how the request to fetch all the popular TV series might look:

GET /api/series?include=producers

We append `include=producers` to let the server know we would like to receive `producer` as part of each `series`. `include` is a standardized way for the `JSON API` to let the server know that it should sideload additional data as part of the main resource. However it’s up to the server what shape sideloaded data will take (i.e. it could be different than if you explicitly use the `/api/producers` endpoint).

REST Response

And this is how server might respond:

{
    "data": [
      {
        "type": "series",
        "id": 1,
        "attributes": {
          "name": "Game of Thrones"
        },
        "relationships": {
          "producer": {
            "data": {
              "id": 1,
              "type": "producers"
            }
          }
        }
      }
    ],
    "included": [
      {
        "type": "producers",
        "id": 1,
        "attributes": {
          "name": "HBO"
        }
      }
    ]
  }

GraphQL example

GraphQL Resources

With GraphQL, you define your resources and queries that can be used to fetch those resources:

  • series:
type Series {
    id: ID
    name: String,
    producer: Producer
  }
  • producer:
type Producer {
    id: ID,
    name: String,
    series: [Series]
  }
  • query to fetch all series with a producer’s name:
query AllSeries {
    series {
      name,
      producer {
        name
      }
    }
  }

GraphQL Request

This is how the actual request might look like:

GET /graphql?query={ series { name, producer { name } } }

GraphQL Response

And this is how the server might respond:

{
    "data": {
      "series": [
        {
          "name": "Game of Thrones",
          "producer": {
            "name": "HBO"
          }
        }
      ]
    }
  }

Our team at iRonin are always on the lookout for the best technologies and practices to help our clients get ahead: whether it’s switching architectures from REST to GraphQL, migrating their apps to more efficient cloud servers, or re-engineering their client side code. If you are interested in developing a new web application or updating your current project, then come and talk to us. Our team of experts stay up to date with the most useful bleeding edge technologies that can save you time, effort, and dollars.

Read Similar Articles