Since its introduction by Facebook, GraphQL has swept the world as an alternative to REST APIs. GraphQL fixes many issues that API developers and users find in RESTful architectures. But it also poses a new set of challenges to overcome. GraphQL is more than just an evolutionary alternative to REST, so this post details the strengths and weaknesses of each, as well as what works best for your application.
Can you smell whats cooking?
RESTful architecture was presented a long time ago as a much simpler approach of server communication that uses simple HTTP protocol without any additional layers and is stateless and type free. This allowed systems to be loosely linked and more tolerant of contract changes between systems, such as those between companies.
REST is simple to use. You make an HTTP GET request to a URL that contains a collection of data that you get in a well-known format, such as XML or JSON. However, despite its many advantages, it has a flaw: caller has no influence over the data structure returned by an API.
GraphQL, on the other hand, executes queries in a single request and receives only particular data. In GraphQL, a set of information is seen in the context of a graph, since the name. And edges reflect the graph's connections between nodes. This enables clear relationships between queries and increases the connectivity between objects.
GraphQL allows users to request data from several resources using a single request. Rather than making multiple requests to fetch data, you can use it to make ad-hoc queries to a single endpoint and access all the required data.
Furthermore, GraphQL allows client to specify the precise type of data to be received from the server. There is nothing more or less. Because of its predictable data structure, it is both readable and efficient.
GraphQL vs REST performance
Take a look at JSON in the example below. It’s an excerpt of a REST call to the SpaceX API that gets a list of all landing attempts. The URL used to make the call is:
https://api.spacex.land/rest/landpads
This excerpt is a single landing attempt extracted from an array of landing attempts that was returned from the REST call.
{
"attempted_landings": "16",
"details": "SpaceX's first east coast landing pad is Landing Zone 1, where the historic first Falcon 9 landing occurred in December 2015. LC-13 was originally used as a launch pad for early Atlas missiles and rockets from Lockheed Martin. LC-1 was later expanded to include Landing Zone 2 for side booster RTLS Falcon Heavy missions, and it was first used in February 2018 for that purpose.",
"full_name": "Landing Zone 1",
"id": "LZ-1",
"landing_type": "RTLS",
"location": {
"latitude": 28.485833,
"longitude": -80.544444,
"name": "Cape Canaveral",
"region": "Florida"
},
"status": "active",
"successful_landings": "15",
"wikipedia": "https://en.wikipedia.org/wiki/Landing_Zones_1_and_2"
},
......
The nine properties in the JSON above are immutable. As a caller, you can't tell the REST API to provide only full_name and wikipedia data. You always get these 9 properties, regardless of whether the REST API returns one landing attempt or 1000 landing attempts.
And this is a big deal, if only you could tell REST to only return the two fields of data that interest you the returned data set would be much smaller. Not only does REST ensures that a lot of uninteresting data makes its way across the network, but it also sits in memory on the client side. You probably noticed this inherent inefficiency at work.
Wouldn't it be great if you could query an API for data according to a data structure you define, asking only for the data you want, as you want it? Fortunately, there is and that way is not REST. It’s GraphQL. 🥰
Take a look at the example below:
It's a query that will run against the same land pad data published by the SpaceX REST API that was previously used in this article. But this time, it's a GraphQL query against the SpaceX GraphQL API, which can be found at api.spacex.land/graphql. The query specifies that it only cares about two fields: full name and wikipedia article.
The data below in is the result of the GraphQL query
{
"data": {
"landpads": [
{
"full_name": "Landing Zone 1",
"wikipedia": "https://en.wikipedia.org/wiki/Landing_Zones_1_and_2"
},
{
"full_name": "Landing Zone 2",
"wikipedia": "https://en.wikipedia.org/wiki/Landing_Zones_1_and_2"
}, .....
Only the full name and wikipedia data are returned. This is the data the developer required, nothing more and nothing less. The GraphQL file is 1.09 KB in size. When we query the SpaceX REST API for land pad data, the JSON array returned is 8.18 KB in size. Remember that the REST API must always return all fields. The efficiency of GraphQL is obvious.
GraphQL vs REST performance analysis
The appeal of GraphQL stems from its increased efficiency. RESTful services, which are typically the result of multiple server queries, frequently return large amounts of unusable data mixed in with relevant information. These inefficiencies also influence the time it takes a client to return all of the requested information.
Because GraphQL reduces the number of endpoints, services can obtain all necessary data with a single call and format it in JSON for quick retrieval. The API server can exchange data using any protocol, including HTTP, HTTPS, WebSockets, and TCP, because GraphQL is transport-layer agnostic.
Unlike multiple endpoints in REST, GraphQL sends all queries to a single endpoint (i.e., HTTP POST). GraphQL schemas are also static: GraphQL does not cover dynamic features like runtime modifications or dynamic type definitions, despite the fact that it allows developers to define schemas for validation and inspection.
As a result, developers must rely on workarounds or custom server implementations, which only increase development time and resource consumption.
Because GraphQL acts as an intermediary to help query the data it receives from various data sources, it has become a standard for API building. By dictating exactly what data is required and giving more control to the client than REST APIs do, GraphQL solves the problem of random data returns that's seen in RESTful service use cases. Like anything else, you should use it in the right scenarios to get high performance with minimal trade-offs.
Let’s now talk about the main advantages and disadvantages of the two API design techniques.
Here are the pros of REST: Mature and proven for decades. Handles various types of calls and supports various data formats, including plain text, HTML, and JSON. Decoupling of client and server architectures provides great scalability for expanding applications easily.
Here are the cons of REST: Prone to under-fetching or over-fetching of data. Multiple round trips of requests required to fetch all the data needed. No specific, standardized methodology of structuring REST APIs
Here are the pros of GraphQL: The presence of a strong type system, which is expressed as a schema, dramatically reduces the effort required to implement queries. The type system stipulates the data structure the server can return. Suitable for avoiding under-fetching or over-fetching of data and for parallel API development for both front end and back end.
Here are the cons of GraphQL: Lacks built-in caching capabilities. Since it always returns an HTTP status code of 200, whether the request is successful or not, this may complicate error reporting and API monitoring.
Conclusion
In conclusion, the skillful API designer should acknowledge how developers will use an API. Not only will this inform which design style best suits the API’s requirements, but it will also result in an excellent API regardless of which design style is chosen.
I hope you enjoy and happy coding! 🥑💖