GraphQL: The Future of APIs
In this article, check out the future of APIs and GraphQL.
Join the DZone community and get the full member experience.Join For Free
When discussing API design, REST or Representational State Transfer is what comes to mind first. It is a standard tool used for data retrieval from the server that accesses data by URLs.
Client applications whilst progressing into the new millennium was relatively simple. That is when REST had been developed and it became a good fit for many applications in due course of time.
It was revolutionary for its time as it brought forward vital API design concepts to the forefront like stateless servers and structured access to resources.
With design getting more complex and increasingly data-driven, these were the following key assessments:
- Efficient data loading was needed as depending on mobile usage rose manifold
- REST was limited in terms of developing an API that was able to cater to a variety of client requirements
- There was an expectation for a swifter feature development
Solving the Shortcomings of REST
IBM, Twitter, Walmart Labs, The New York Times, Intuit, Coursera were some of the first companies to have migrated from Representational State Transfer or RESTful to GraphQL APIs for internal usage and they claimed that the switch was a successful one.
Some like AWS, Yelp, GitHub, Facebook, and Shopify went a step further because their migration from RESTful to GraphQL APIs was for both external and internal reasons.
But Are You Aware of GraphQL?
Simply put, GraphQL is an open-source query language and the protocol for APIs. You can think of GraphQL similar to SQL which is applicable only for APIs instead of databases.
It is the modern alternative for REST-based architecture. Unlike REST, GraphQL allows for requesting specific data that a client needs, departing from the fixed data structure approach.
The Reason for GraphQL Hype
Does GraphQL have any real merit and can it be a key game changer?
Interestingly, all of the companies that have been mentioned so far that have the following in common:
- They have several clients that also includes mobile
- They are planning to shift to or are already using a microservices architecture
- Their dependence on RESTful APIs multiplied and became more complex
- They are looking at ways to remove dependencies of their client teams and move it to API teams
- They care about the developer experience and value good API documentation
As GitHub Engineering rightly puts it, “Using GraphQL on the frontend and backend eliminates the gap between what we release and what you can consume. We really look forward to making more of these simultaneous releases.
GraphQL represents a massive leap forward for API development. Type safety, introspection, generated documentation, and predictable responses benefit both the maintainers and consumers of our platform.
We’re looking forward to our new era of a GraphQL-backed platform, and we hope that you do, too!”
A pre-defined schema is offered to clients by the GraphQL server. This is basically the model data that can be retrieved from the server where the schema acts as the connector between the server and the client whilst defining the process of accessing the information.
The basic elements of a GraphQL schema are written down in SDL or Schema Definition Language. It explains all sorts of objects that can be requested on that specific server including the fields that they possess.
The queries that are permitted to be requested such as what types of data can be fetched and the relationships between these types are defined by the schema.
In fact, the GraphQL schema can be developed and an interface can be created around it with any programming language.
To make sure that the server is able to respond to the query, the client can validate their query against the schema. You will be able to predict the outcomes depending on the shape of the GraphQL query that closely resembles the result.
This additionally scrubs out any unwelcome surprises, for example, incorrect structure or unavailable data.
At the point when the GraphQL operations reach the backend application, the interpretation is made against the complete schema. Only then is the data for the front end application is totally and accurately resolved.
In a nutshell, there are three primary operations in play with GraphQL. These are:
- The query for reading data
- The mutation for writing data
- Subscription for automatically receiving real-time data over time
The client-driven approach has made GraphQL so attractive to developers. This is simply because of the progress made in querying in one request and receiving the data that is required instead of the complete set.
The data type being returned is decided when the control of the data is handled over to the clients' GraphQL.
On the other hand, REST encounters the issue of over-fetching. The server defines the data that is available for each resource.
Even if only a part of the data is needed, the client will have to request the entire information in a resource via repeated network requests.
GraphQL Advantages in Comparison to REST
GraphQL and REST are both specifications that are needed to build and consume APIs. A common feature in both technologies is that they can return JSON data in the request when they both retrieve resources by sending queries.
Additionally, they can both be operated over HTTP. Moreover, the endpoints of REST and GraphQL fields are more or less similar because they act as entry points into the data that call functions on the server.
In spite of the commonalities, there are a few stark differences with their conceptual models. GraphQL is built on graphs whereas REST is developed on file.
Take a look at how the developer experiences of building and consuming an API differs.
In terms of speed, GrapgQL is way faster as you can actually minimize time by cutting down on your request by choosing the fields that you want to run the query on.
These are the obvious benefits of utilizing a GraphQL API instead of a REST API.
1) Good Match for Multifaceted Systems and Microservices
GraphQL is able to unite and hide complexities by integrating multiple systems behind the API. Fetching the data from the current systems and then packaging them in the GraphQL response format is the job of the GraphQL server.
For third-party APIs and legacy infrastructures that have been on an expansion spree over the years, this is specifically relevant as it presents a maintenance burden.
Merging multiple microservices into a GraphQL schema can assist in handling communication between them too when migrating from a monolithic backend application to a microservices architecture.
It can be consolidated into a global schema through one GraphQL API gateway even though each microservice defines its own GraphQL schema and has its own GraphQL endpoint.
2) Obtaining Information With A Single API Call
Multiple endpoints need to be combined by the developer to collect all needed data because REST is scattered around individual endpoints.
This is the main difference between GraphQL and REST. The developer can request the required information with just one API call whereas GraphQL concentrates on the primary task.
3) No Over and Under Fetching Difficulties
There is an element of erratic in the responses received from REST. Either they contain less data or too much data making another query request inevitable. This problem has been solved by GraphQL as it fetches the exact data that is required in a single request.
4) Adapting Requests to Your Requirements
There are only specific endpoints, their related functions, parameters, etc. that can be requested by a REST API documentation by a developer.
On the other hand, GraphQL is able to describe data types, fields and any interaction points between them. This allows developers of GraphQL to customize the request to access the necessary information.
5) Authentication and Type Checking Out-Of-The-Box
The introspection feature by GraphQL enables navigation into the types and finding the schema to make sure that apps only request for what is possible and in the right structure.
Having said that, developers are able to add new fields to current queries with the help of a GraphQL IDE without any further validation of the data format. All that needs to be done is to write resolvers by the developers.
6) Auto-Generating API Documentation
The documentation is kept in sync with API changes with GraphQL because it is tightly entwined with code. Therefore, a change even in a single field, query or types triggers a change automatically in the documentation too.
7) API Evolution without Versioning
REST offers several API versions that it is an evolving API which means that developers have to keep the old version until the switch to the new version has been made.
GraphQL skips this step as aging fields can be removed from the schema without influencing existing queries at a future time or date.
This ensures that GraphQL’s evolving version allows constant access to the app’s new features, therefore, encouraging a server code that is cleaner and easier to maintain.
If the need for reuse arises, then fields used in multiple queries in GraphQL can be shared at a higher component level. These are known as fragments that enable you to access various types of data whilst still adhering to the same schema field.
9) Detailed Error Messages
To ascertain what has gone wrong and what needs to be done to handle it, checking the HTTP headers for a status of the response is adequate in REST.
However, in GraphQL, if there is an error during processing, a detailed message is provided by the backend which also includes resolvers. These refer to the exact part of the query where the fault lies.
Choose which functions and their workings to showcase when creating a GraphQL schema. Comparing this feature to REST views, it tends to be all or nothing.
Hence, the idea is that individual views should possess the knowledge of what can or cannot be made visible under certain situations. And this is not a simple feat to achieve.
Putting It Together
It would be incorrect to say that GraphQL can completely substitute REST since the former is a tool, whereas the REST is an architectural pattern. Which one will be a better fit will depend on their unique interaction scenarios.
Opinions expressed by DZone contributors are their own.