The usage of APIs has seen a tremendous growth. As mobile apps became more popular, there was an obvious need to de-link the backend of the application from the front-end. Using APIs as the backend made developing and launching mobile apps easier.
This important development made its entry in the web app development space too, as client-server model became more popular here. Once again, APIs were the important components in the server-end.
The result of all these is that APIs are now present in most of the software that are developed nowadays. This widespread usage of APIs also showed a few drawbacks in how APIs were built and consumed, which spawned innovations like REST and GraphQL.
If you are planning to build and consume APIs in your proposed application, then you could be wondering whether to GraphQL vs REST. In this guide, we compare the two, so that you can make an informed decision.
A brief history of how REST and GraphQL emerged
Let us first understand a bit of history behind the emergence of REST, which stands for Representational State Transfer, and GraphQL, i.e., Graph Query Language. This will help you to appreciate the challenges they intend to address and how they fit in your context.
Before REST
We had protocols like RPC, SOAP, and CORBA before it became a standard to use RESTful APIs. Using these protocols involved several complexities, e.g., if you used CORBA, then any update to the interface required changes to both the client and server.
This made updates to the interfaces costly when you used CORBA, moreover, the interfaces had a high degree of specificity. This meant that if you were rolling out a new version of the interface, then all clients needed to upgrade at once.
Protocols prior to REST required complex client libraries, which would help in serialize or deserialize the payload in an API. E.g., SOAP uses Web Services Description Language (WSDL), and this reduces its interoperability. If you had to implement SOAP, then you had to implement a complete protocol including error handling, security etc.
SOAP can run on HTTP, TCP, etc., and this afforded a lot of abstraction. However, the rigid contract between the client and server increased the complexity. In summary,
In summary, the protocols prior to REST had rigid contracts between the client and server, and any minor change required all clients to upgrade at once. This increased the complexities in building and consuming APIs.
The Advantages of REST
The RESTful architecture emerged in 2000, and it offered a simpler way for a computer to interact with another. This architecture utilizes the HTTP protocol for communication between computers, and this communication is stateless, i.e., the server doesn’t store any state about the client session on the server side.
The client stores the client session, therefore, the server can service any client at any time. This was an improvement over the earlier protocols since it helped in scaling the APIs.
With the emergence of RESTful architecture, application systems could now be loosely coupled. Business contracts between two organizations change often, and the RESTful architecture made it easier for them to implement these changes. Even more importantly, RESTful APIs help the client and server to be loosely coupled, thus making mobile and web app development much easier.
Programmers working with someone else’s RESTful API doesn’t need to use any special libraries, and they don’t need to implement any special initialization. When using RESTful APIs, an application can send requests to another using common software like cURL and web browsers.
REST uses HTTP data resources, i.e., URIs, and conventions, moreover, it uses CRUD HTTP verbs like GET, PUT, POST, and DELETE. Developers using an API will need to design their data model, however, they can use HTTP conventions to make their programming easier. With REST, the data contracts are loose, while REST itself is coupled tightly with HTTP.
The disadvantages of REST, and why GraphQL emerged
While REST offered many advantages to developers and became the de facto standard for businesses that deploy APIs, it also has a few disadvantages. These disadvantages arise from the fact that the server creates the representation of the resource, and the response to the client uses that.
We have seen a sharp increase in the usage of mobile devices since 2010. Some mobile-devices were low-powered, moreover, the mobile networks were slow. Server-defined representations of resources didn’t serve this scenario well.
RESTful APIs often returned more data than what the client needed, alternatively, the client had to make multiple API calls to get all the data it needed. Developers also had to design the API endpoints keeping the front-end views in mind, and changes to the front-end views required changes to the API endpoint.
The result was less flexibility. Many different front-end frameworks emerged with the growth of mobile usage, moreover, there was an increase in platforms running client applications. The lack of flexibility in RESTful APIs impacted faster product iteration, and we will explain this in more detail shortly.
These led to the search for an alternative to REST, and Facebook created GraphQL in 2012. GraphQL is a cross-platform data query and manipulation language for APIs. It’s a runtime for executing queries against data, and Facebook open-sourced it in 2015. The latest stable release of GraphQL was released in June 2018.
The GraphQL Foundation, a newly established organization hosted by the Linux Foundation governs developments around GraphQL. GraphQL servers are available for multiple popular languages, e.g., Java, JavaScript, Ruby, Python, Perl, C#, Go, etc.
The popularity of GraphQL grew rapidly. E.g., The State of JavaScript 2018 report mentions that only 5% of developers surveyed had used it in 2016, however, 20.4% of developers used it in 2018.
GraphQL vs REST: Similarities and differences
Before we explain the similarities and differences between GraphQL vs REST, let’s understand that GraphQL doesn’t necessarily have to replace REST. They can coexist in one project. We analyze the similarities and differences between GraphQL vs REST concerning the following aspects:
Resources: How REST vs GraphQL treat them
The defining concept of REST is the resource, and it identifies resources as URLs. When developers want to retrieve a resource in their application, they send an HTTP GET request to the said URL. Since most APIs use JSON, developers will likely get JSON data as the response.
Up to this point, GraphQL and REST are similar. GraphQL also has the concept of resources, and it identifies them as URLs. Developers can send HTTP GET requests to retrieve the resource, and they get JSON data as the response.
Over to the differences now. When developers consume REST APIs in their application they call an endpoint, and this is the identity of the object. However, it’s different with GraphQL since how the resource is fetched is separate from the identity of it. GraphQL developers define “types” for information they want to fetch, subsequently, they create queries in their schema specifying what information they want to retrieve.
The other key different concerns with the shape and size of the resource, and in the case of REST, the server determines it. When you use GraphQL, the server only tells you what’s available. You write a query specifying what information you want to retrieve.
URL routes in REST vs GraphQL schema
When a business designs APIs, it takes care to make the API predictable. This means that developers using this API should know exactly what should they call, and what to expect as response. API documentation standards stress upon this information being very clearly presented so that the information can be easily used by application programs.
Both REST and GraphQL requires such documentation, therefore, we can see a similarity there. However, the nature of this documentation varies between GraphQL vs REST. In the case of REST, a list of endpoints describe the API, therefore, developers consuming the API needs to determine which endpoint they should call. Subsequently, they use different HTTP verbs for read and write.
Developers using GraphQL doesn’t use endpoints since they use the GraphQL schema. A GraphQL schema has different initial types like “Query” and “Mutation”, and developers specify their intended operation using these keywords.
Developers can use the same fields on the “Query” type as they would use in the endpoints in case of REST. This is yet another similarity between REST and GraphQL. However, GraphQL developers can then use complex GraphQL queries to access additional data. These queries utilize the relationships defined in the GraphQL schema.
Route Handlers in REST vs Resolvers in GraphQL
After developers call an API, there are pieces of code that execute on the server. These pieces of code might compute something, call another API, load data from a database, etc., REST and GraphQL have their own ways to implement this, and there are both similarities and differences between them.
When an application makes a REST API call, the execution utilizes route handlers, which are functions for specific URLs. They work as follows:
- The server receives the API call request, and it retrieves the URL path and the HTTP verb, e.g., GET.
- There are functions registered for the API, and the server finds it by matching the verb and path.
- The server executes the function and produces a result.
- It’s now time for the API library to serialize this result, and it adds a response code and header. Subsequently, it sends the result to the client.
GraphQL follows the same practices in concept, however, the implementation is different. There are no functions for specific URLs, rather, GraphQL uses functions for for a field within a type. E.g., a GraphQL function may implement a field within a “Query” type.
These GraphQL functions are called resolvers, and they work as follows:
- Upon a GraphQL API call, the server received a request and retrieves the GraphQL query.
- It examines the query, and calls the resolver for each field in that query.
- The resolver returns a result, and the GraphQL library and server adds this result to a response. The response is then sent back to the client.
GraphQL resolvers allow processing multiple fields in one request, moreover, developers can call the same field multiple times within a query. Using this flexibility, programmers can create nested queries using these resolvers since they are attached to various GraphQL types.
Data fetching with GraphQL vs REST
The differences between GraphQL vs REST we described above influence how the data is fetched. A typical usage of REST API will fetch data by calling multiple API endpoints, and the server will return all data in those endpoints.
REST
GraphQL
As we have explained, GraphQL uses queries, schema, and resolvers. Developers can specify the exact data they need, moreover, they can create and execute nested queries. This difference in data fetching is a significant, as we will soon explain.
Why GraphQL over REST?
GraphQL offers several advantages over REST, which are as follows:
Resolution to over-fetching and under-fetching
As we have explained above, apps using REST APIs call endpoints, and the entire data in that endpoint will be returned in the JSON format. This results in over-fetching as well as under-fetching.
Even if an application needs only a few fields from an API endpoint, it gets all the data. This includes data that may be unnecessary for the app, therefore, we call it overfetching.
On the other hand, a REST API endpoint may not have all the data that an application needs, therefore, the application doesn’t get everything it needs in one data fetching exercise. This is under-fetching, and the application will need to make multiple requests to different API endpoints.
In different ways, over-fetching and under-fetching can cause performance and scalability issues. GraphQL with its queries, schemas, and resolvers enable developers to design API calls that meet their specific data requirements. This way, GraphQL resolves the over-fetching and under-fetching challenges.
Faster product iterations on the frontend
A common practice while designing REST APIs is to design the API endpoints according to the views in the application. This helps the application to get the data required for a view by simply accessing the API endpoint that corresponds to the view.
While it serves many purposes, it can be a bottleneck when the application needs quick iterations on the frontend. Such iterations might require more data in the frontend, or they might require less data.
This requires changes to the API endpoints every time the frontend changes. Such frequent changes to the backend impact the ability of the development team to change the frontend, and this reduces the productivity.
GraphQL addresses this, thanks to its flexibility! Developers can write queries specifying their data requirements, and the iterations for developing of the frontend can continue without having to change the backend.
GraphQL enables better analytics on the backend
Applications that use REST APIs get the entire data in an API endpoint, as we have explained. The application owner can’t gain insights on the usage of specific data elements since the entire data is returned every time.
GraphQL, on the other hand, has queries, and developers use them to retrieve specific data elements. This enables the application owner to gain insights about which data elements are in demand, moreover, they will know which data elements aren’t being used by clients anymore.
As we have explained earlier, GraphQL uses resolvers, and they implement particular fields in a type. Application owners can track the performance of the system at the level of these resolvers, and find out whether the system needs performance tuning. This granular level of performance monitoring is an advantage of GraphQL over REST.
The advantages of the GraphQL schema
The schema of GraphQL uses the Schema Definition Language (SDL), and the type system of GraphQL sets out the types in an API. The schema includes all the types used in an API, and it defines how a client should access the data on the server.
After the development team defines a schema, both the frontend and backend teams know the structure of the data. These teams can now work in parallel. The frontend team can create dummy test data and test their application, and when it’s ready, the application can start using the real API. This helps to improve the productivity of the team.
Conclusion
Both REST and GraphQL are prominent ways to design how an API will function and how applications will access data from it. While REST had significantly simplified the work of developers with its standardized approach, it does have a few drawbacks. GraphQL, with its queries, schemas, and resolvers offer more flexibility, moreover, GraphQL can offer better performance.
REST still holds on it own though, and you can use both REST and GraphQL in a project. Carefully analyze your application, data, and performance requirements, so that you can choose appropriately.
Are you looking for Mobile/Web app Development services? Contact us at hello@devathon.com or visit our website Devathon to find out how we can breathe life into your vision with beautiful designs, quality development, and continuous testing.
John
Very well explained about REST and GraphQL, Thanks for the article.