Table of contents
No doubt GraphQL has been around for quite sometime, developed since 2012 by Facebook before being moved to GraphQL Foundation, hosted by the non-profit Linux Foundation to be open-source. Since its publish in 2015, GraphQL has gained quite the popularity it deserved and raised more questions and debates on whether to use GraphQL, REST or a combination of both in new projects.
So let's start by breaking it down to APIs, what is REST, GraphQL and how are they different?
What is REST API?
A REST API, is an API (Application Programming Interface) conforming to the REST architectural style or REST standards and design principles those are:
Uniform interface: All Requests for the same resource should look the same.
Client-server decoupling: Server logic should be separated from the client-side and only the resource request URI should be exposed to the client-side.
Statelessness: Server-side has no sessions and cannot have a state, each request should have all the data needed for processing.
Cacheability: If possible, server should cache resources returned to the client-side and If applicable, the response should contain information about whether caching is allowed.
Layered system architecture: Server-side can be multi-layered so that neither client-side nor the server can distinguish whether they are communicating directly or through a broker.
How REST APIs work?
REST APIs utilises methods to retrieve and manipulate data through HTTP requests to preform what is known as CRUD Operations ( Create, Read, Update, Delete).
Methods exposed by REST are:
GET: reads a specific resource.
POST: creates a new specified resource.
PATCH: modifies a resource.
PUT: updates/replaces a resource in a collection.
DELETE: deletes a resource.
A typical REST API request includes a method, headers (key-value pairs to include information about the request, caching details and response types) and a body that could contain the payload of the request..
REST APIs' requests can return JSON, HTML, XLT, Python, PHP, plain text or even files.
Advantages of REST APIs
REST APIs are simple to use and have standardised format, which greatly simplifies and accelerates implementations.
By using Restful APIs, you get the standardised HTTP status codes which are universal, for example a 404 mean a resource couldn't be found, 500 is an internal server error. Full list can be found here.
Disadvantages of REST APIs
Having multiple endpoints means the client-side has to execute several requests to get their data
REST is not best suited for complex environments or for fetching a large amounts of data
Wasting network and memory resources as a result of over-fetching data.
What is GraphQL?
GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL utilises three types of methods; Query, Mutation and Subscriptionto read and manipulate data, whereas Query replaces GET Request in REST and Mutation replaces PUT, POST, PATCH and DELETE. Subscription is used to add WebSockets functionality.
Advantages of GraphQL
GraphMa: you get served what you ask for
Queries in GraphQL are expressive, instead of returning back the whole resource, you can get what you have asked for and only what you have asked for. example follows to retrieve only the first name and _id of the user.
user() {
_id
name {
first
}
}
I want a resource, or two.
In contrast with the original RESTful API way of talking to multiple endpoints to retrieve different resources, GraphQL relies on the idea of hitting one endpoint. Actually your whole server may have one endpoint that you hit to retrieve different resources, in the same time. querying different resources definitely helps with the speed of making requests making it further quicker for slow connections.
Example follows of a multiple resources' request (requesting posts with the user):
{
user {
name {
first
last
}
posts {
title
}
}
For a conventional REST API way we could have implemented the previous request by hitting two endpoints:
GET /user/
GET /posts/?id=user_id
With Schemas come Types
Under the hood, GraphQL uses types to ensure you ask only for what you can ask for. Declare types of the resources you would provide.
Types for the previous query would look like this:
type Query {
user: User
}
type User {
name: UserFullName
posts: [Post]
}
type UserFullName {
first: String
last: String
}
type Post {
title: String
}
Disadvantages of GraphQL
Status codes? who uses that?
Apparently, GraphQL doesn't believe in status codes for the response. GraphQL believes in 200:OK. All responses returned by GraphQL will return status code of 200 independent the request was successful or not. If the request went unsuccessful though you will get a top-level errors key with the actual error is its value, so make sure to check if the request has errors before you proceed with the response logic.
No Caching
GraphQL does not include built-in caching support, you will need to relay on another libraries like Redis if that is your case.
Complexity
Replacing the easy-to-understand REST APIs uniform interface with query schema definitely comes at a price of learning curve for newbies, although not steep and could be worth it.
So, Which should I use?
GraphQL is great for being strongly typed, and self-documenting based on schema types and descriptions and integrates with code generator tools to reduce development time. Both have their advantages and disadvantages, it is a matter of weighing the pros and cons, for example, If speed, performance and network bandwidth are your main concerns, go for GraphQL, if ease of use or returning media files are your concerns, go for REST.
Performance
In terms of performance, GraphQL obviously has the upper hand, for avoiding over/under-fetching, GraphQL allows you to get what you ask for.
Security
When talking about GraphQL vs REST in terms of security, REST provides several ways to enforce the security on your APIs, including using methods like HTTP authentication through HTTP headers carrying JSON web tokens.
Fetching
By Fetching all you could ask for through one request (Query) hitting one endpoint is clearly a spot-on for GraphQL.
Caching
If implementing caching on data is your concern, you'll be more likely to use REST than adding a library to manage cache like Redis in your code.
Error Handling
No doubt that the RESTful APIs provide a more convenient way of handling errors that can be handled each on their own by their status codes in contrast with GraphQL always returning 200:OK response even if there was an error with the request.
Mobile on mind?
GraphQL works best for businesses aiming to build mobile-responsive solutions as it can guarantee the application to be responsive with low latency due to its simple architecture.
Conclusion
So I have covered all the differences, take-ons, pros and cons of both GraphQL and REST APIs. As for now you can put both into consideration and head-to-head decide which one to choose solely based on your project requirements. As a matter of fact, both will do a great job implementing the communication between your server side and client side, but one of them will always do a better job handling an aspect of your app, So, it is a matter of weighing between pros and cons of both and deciding which are more of a concern to your architectural design. A perfectly-designed system could actually have a combination of both.