GraphQL vs REST API

Introduction

GraphQL is currently being presented as a replacement for REST API. It promises better performance, better flexibility for API consumers, no-more-over fetching data, etc..
REST API has been used for quite a while and it has been solving many use cases for HTTP APIs. In this article, we will be going through a few of the major differences between GrapQL and REST APIs.
Before that let's understand What is REST API and GraphQL.

REST API

API is a code used by two software programs to communicate with each other. REST is an acronym for REpresentational State Transfer. REST API is an architectural style that follows its own defined constraints.
  • Client-Server - client application and server application MUST be able to evolve separately without any dependency on each other. The client should be calling the server through resource URIs.
  • Uniform Interface - MUST decide APIs interface for resources inside the system which are exposed to API consumers and follow religiously. A resource in the system should have only one logical URI, and that should provide a way to fetch related or additional data. Whenever relevant, a resource should contain links (HATEOAS) pointing to relative URIs to fetch related information. Also, the resource representations across the system should follow specific guidelines such as naming conventions, link formats, or data format (XML or/and JSON). All resources should be accessible through a common approach such as HTTP GET and similarly modified using a consistent approach.
  • Stateless - Make all client-server interactions stateless. The server will not store anything about the latest HTTP request the client made. It will treat every request as new. No session, no history.
  • Cacheable - In REST, caching shall be applied to resources when applicable, and then these resources MUST declare themselves cacheable. Caching can be implemented on the server or client-side. 
  • Layered Systems - REST allows using a layered system architecture where once can deploy the APIs on server A, and store data on server B and authenticate requests in Server C. 
  • Code on Demand - this constraint is optional. Most of the time, you will be sending the static representations of resources in the form of XML or JSON. But when It is needed, it can return executable code to support a part of your application, e.g., clients may call your API to get a UI widget rendering code. It is permitted.
Example of a REST API:
/customers
/customers/{customerid}
/customers/{customerid}/orders
/customers/{customerid}/orders/{orderid}
One more thing to note that all the REST APIs are HTTP APIs but all HTTP APIs might not be REST. 

GraphQL

GraphQL follows the same set of constraints as REST APIs, but it organizes data into a graph using one interface. Objects are represented by nodes (defined using the GraphQL schema), and the relationship between nodes is represented by edges in the graph. Each object is then backed by a resolver that accesses the server’s data.
GraphQL is a query language for APIs. A big advantage of GraphQL is it allows clients to dictate the form of data returned by the server. This solves over-fetching and gives API developers insight into which fields are used by a client.
There are two major GraphQL clients available at the moment. The first one is Apollo Client, which is a community-driven effort to build a powerful and flexible GraphQL client for all major development platforms. The second one is called Relay and it is Facebook’s homegrown GraphQL client that heavily optimizes for performance and is only available on the web. A small comparison between the two clients are:

Relay
Apollo
FrameworksReact, React-NativeFramework Agnostic
GraphQL APICustom SchemaFlexible with any schema
EffortCaching and other features inbuilt but the initial learning curve is hugeMore manual work
Subscription - GraphQL feature for WebSocketNo subscription supportsubscription support available using subscriptions-transport-ws
Schema CheckBabel is used to checking schema at build timeOptional tools

Example of a typical GraphQL query would be:


GraphQL vs REST API

Let's compare now GraphQL and REST API features:



GraphQL
REST API
Concept
It is a query language, a specification, and a set of tools that operates over a single endpoint using HTTP.
A REST API is an architectural concept for network-based software
Design
It is designed client-centric so that UI can dictate what objects, fields a server should return. Difficult for consumers to understand how the server implementation is done.
It is designed server-centric where the server decides what objects, fields to be returned. Easy for consumers to understand how to use it.
Endpoints
GraphQL uses a single endpoint to retrieve all the resources information for UI. e.g.
/customers
REST uses one URI per resource
/customers
/customers/{customerid}
/customers/{customerid}/orders
/customers/{customerid}/orders/{orderid}
Fetching Data
It fetches the data exactly what the client needs. No over or under fetching. GraphQL uses its query language to tailor the request to exactly what you need, from multiple objects down to specific fields within each entity. 
REST recommends retrieving all the information of a resource using the URI. It may over fetch for a client which needs only a few of the fields for a resource.
For example, an API /customers is designed to return the customer's first name, last name, and other information of all the customers. What if a UI screen has a need to just get Customer Id to create hyperlinks on the page. There is no way it can fetch only customerid. Thats over-fetching. Similarly, there can be a under-fetching scenario as well.
WebSocket
GraphQL supports the WebSocket using the subscriptions-transport-ws extension. It is a GraphQL WebSocket server and client to facilitate GraphQL queries, mutations, and subscriptions over WebSocket. Apollo Client also supports it.
REST doesn't support WebSocket
HTTP Methods
GraphQL has query and mutation to retrieve, create and update the data.
There is no direct method to delete the object in GraphQL. It needs to be handled by GraphQL Clients like updateQueries in Apollo. Logic needs to be written to remove the particular object from the list and update the object with updateQueriesThere are side effects of this approach as all the cache queries will need to be refetched to sync them with the latest data.
REST supports many HTTP methods like GET, POST, PUT, PATCH, DELETE.
Tools
GraphQL has very limited clients that support - Apollo and Relay are the most common ones which are mostly React native.
REST is supported by each framework by now, NodeJS, Spring, .NET, etc..
Learning Curve
GraphQL is comparatively new and requires initial learning
REST is known to every newbie in IT.
Performance
If an application has a need to retrieve data from nested resources, GraphQL is much better in performance as it can retrieve specific fields from the root and nested nodes.
Compare to GraphQL, it needs to call multiple URIs to retrieve the information which takes a performance hit.
Please note, developers are building APIs where a URI is returning root and nested resources with a single URI. However, it is not compliant with REST and they should be called HTTP API. And these APIs can become very tightly coupled with a particular consumer.
Flexibility
GraphQL provides the flexibility of retrieving data from the Client side. If an application has rapid changes at Client-side with frequent data changing needs, GraphQL is best to apply there.
If an application needs flexibility at the Server-side where more changes are happening at the Server-side adding new features, REST is recommended as it will avoid testing other resources and can avoid impact to them.
Caching
GraphQL supports client-side caching. e.g. Apollo Client. It is much more powerful than REST caching as it can cache the whole tree of the data graph and even can do partial caching at objects/nodes level.
REST supports both server-side and client-side caching.

Summary

GraphQL and REST both are good at what they offer. As REST has been there for quite a while, it has more tools, community support and knowledge around it. GraphQL has been picking up the lag and becoming popular due to its benefits of improving the performance of APIs. However, both are good and provide pros and cons. Read out the high-level differences mentioned above and take the decision accordingly.

No comments: