When to use GraphQL and REST for your web project? GraphQL and REST are both popular options for building APIs, but they have different strengths and weaknesses. Choosing between them depends on the specific needs of your project. Here we will consider the difference between GraphQL and REST, benefits of GraphQL over REST, and other interesting peculiarities. Stay tuned!
What Is GraphQL?
Whether you are a front-end, back-end, or mobile engineer, you have probably heard about GraphQL. There’s a “Graph” part in its title — has it something to do with the graph theory from mathematics? In fact, it has, so let’s briefly observe the theoretical concept first.
Graph theory is a study that focuses on graphs that represent mathematical structures made up of nodes (also called points or vertices) connected by edges (also known as lines or links) and used to represent relationships between objects. Graphs can illustrate many everyday life concepts and processes.
Let’s take a look at a real-world example of a graph - the social graph. It portrays us and our relations with other people and objects (hobbies, services, companies, etc.).
A lot of data in modern applications can be represented using a graph. All applications can operate on these graphs - they read existing data from and write new data to them.
Now that the meaning of the “Graph” part in GraphQL is clear, let’s proceed with QL. QL stands for the query language. Thus, GraphQL can be defined as a query language and a server-runtime technology that operates on the basics of graph theory - it traverses your data graph to produce a query result tree. GraphQL is all about seeing your data as a graph and then querying that graph.
Created by Facebook in 2012, it was used only within its mobile app ecosystem but went open source in 2015 and rapidly gained recognition. GraphQL is mostly involved in the context of web technologies these days, even though it has been developed primarily for native mobile environments.
Is GraphQL the better version of REST?
For a long time, there has been one standard approach for exposing data from a server - REST. An API designed using this architecture pattern is known as REST API, and it was a perfect fit for many applications back in the day.
The main idea behind REST APIs is operating with multiple endpoints that return fixed data structures. In the example below, with REST, we would have 2 separate endpoints with data about books and authors.
Now there is a GraphQL vs REST battle. Developers may ask - why should we use GraphQL when we already have REST API? This question leads us to the reasons for creating GraphQL. The API landscape has radically changed over the past decade, and REST was no longer covering some crucial aspects of app development.
Product Discovery Lab
Free product discovery workshop to clarify your software idea, define requirements, and outline the scope of work. Request for free now.
Engineers at Facebook were facing numerous limitations of the REST architecture at that time: a giant amount of connected data was stored in different databases, which required the creation of many REST endpoints to retrieve that data. But let’s imagine how tremendous was the amount of data retrieved - many redundant fields were returned among the requested ones, which caused plenty of drawbacks, including a poor speed of requests for low-powered devices and sloppy networks.
It was obvious that there should be a new approach to client-server communication. This is where GraphQL enters the game - it enables declarative data fetching where an API returns precisely the data a client asked for, nothing less or nothing more.
The approach that’s taken in GraphQL is radically different from REST and is considered a more efficient, powerful, and flexible alternative to RESTful APIs that provides new benefits while serving the same purpose. If you think about GraphQL vs REST, consider the pros and cons of each technology.
How does it work?
GraphQL has its own type system that’s used to define the schema of an API. The syntax for writing schemas is called SDL (Schema Definition Language).
Once the schema is ready, resolve functions (also called resolvers) should be created for each type. This is done to connect the data to the graph.
Once you are all set with schema and resolvers, it’s time to write queries. Based on the graph data modeling with the schema at its core, GraphQL has three primary operations:
- Query for reading data
- Mutation for creating, updating, and deleting data
- Subscription for automatically receiving real-time data from a server.
Let’s see how getting data with GraphQL API works compared to REST API. Let’s say we need to retrieve specific data about an author (first name and last name) and his/her books (only the title field). Typically, we would make 2 requests to 2 separate endpoints with REST API:
- /authors/:id
- /authors/:id/books
We would get responses of a fixed size containing all the fields that backend developers added there, even if we needed only a few fields.
But you will not have this result when calling the GraphQL API. You should write and send only one query describing what data you need. The result will contain exactly what you asked for.
Benefits of GraphQL
Now let’s talk about the key benefits of GraphQL - what makes it so popular and highly appreciated by developers these days?
Data fetching control
When to use GraphQL over REST? One of the key advantages of GraphQL API over REST APIs is data fetching control with a client-driven approach. While REST API architecture often performs over-fetching (getting more information than is actually required) and under-fetching of data (getting less information than is required) in requests, GraphQL allows clients to control what data they want to get. With the latter, you send a single query with the concrete data requirements and receive the server's response where these requirements are fulfilled.
Performance
Difference between GraphQL and REST lies in their performance. With GraphQL, a large amount of data may be gathered with one API call, which leads to great performance metrics compared to RESTful APIs.
Strongly-typed schema
GraphQL uses a strong type system to define the capabilities of an API. Types are stored in GraphQL’s schema and are supported by the SDL (Schema Definition Language) - a special syntax for writing such schemas. This allows developers to create API on their own: they see what the schema can query and how the data is set up there.
Even more - there’s no need to validate the data format, as GraphQL automatically does it for you. Thus, developers are allowed to develop stable APIs that are less error-prone.
Better developer experience
GraphQL speeds up the development process by providing a single endpoint that grants a single centralized data access point that leverages the API architecture. In addition, GraphQL offers easier coding with the data right next to UI, reusable fragments, and less thinking of error handling.
As the GraphQL API is tightly synchronized with code, once a field, type, or query changes, so does the documentation. This directly benefits developers since they have to spend less time documenting an API.
GraphQL offers a new type of operation - subscriptions. It allows subscribed clients to receive real-time messages from a server when some data is changed.
Community
GraphQL has a huge, fast-growing community with many engineers switching to it. The GraphQL ecosystem grows both horizontally by offering multiple programming languages and vertically, with libraries on top of GraphQL. Many companies known worldwide use GraphQL in production - Facebook, Twitter, GitHub, Shopify, Airbnb, Coursera, and others.
Challenges of GraphQL
Although GraphQL is a decent alternative to REST, it’s not a replacement yet and has its own pitfalls, here are some of them:
Complex query support
It is important in GraphQL vs REST comparison that even though GraphQL was created to enable making one API call for a big amount of data, this sometimes may lead to performance issues as there may be too many nested fields in one query. It might be a better idea to use REST APIs for complex queries - although multiple network calls can take up more time, having multiple endpoints with fine-tuned, specific queries would be safer from the server maintenance perspective.
A caching issue
Caching plays an important role in app development, as it helps to reduce the amount of traffic to a server by storing the content of a request close to the client. Unfortunately, GraphQL doesn’t provide caching support out-of-the-box and requires using third-party libraries to handle it.
An overkill for small apps
REST vs GraphQL? GraphQL offers many perks for engineers, yet it may not be the best approach for small applications development. Using GraphQL for small apps may be a waste of time that would add unwanted complexity and redundant dependencies to your project. Sometimes it’s better to go for a classic REST architecture, especially with resource-driven apps that don’t need flexible queries and don’t operate with vast amounts of data.
Get inspired by our recent blog post about Android biometric implementation.
When should you use GraphQL?
GraphQL is powerful enough to implement several design patterns on new or existing web services. It would make a perfect fit in such scenarios:
Composite pattern
When implementing a Composite pattern, you typically want to aggregate your data from multiple sources (third-party services, databases, etc.) into one convenient API. GraphQL would be a great solution to this problem.
Proxy Pattern
Proxy pattern is about attempting to add a new piece of functionality to an existing project. GraphQL might work here as well - it wouldn’t conflict with your old API, so you can add a new logic on top of the existing one and use them simultaneously.
Facade Pattern
Facade pattern is in charge of simplifying an existing API. GraphQL is powerful enough to do that - you can gradually re-write your project’s API for GraphQL API without losing previous functionality, and even more - the capabilities of your API may be enlarged.
Apps with many occurrences of nested data
If you are working on a project such as an e-commerce platform, where many layers of nested data need to be fetched in a single call, GraphQL would be the best tool here. In fact, one of the biggest e-commerce development platforms, Shopify, provides developers with GraphQL API for working with its storefront data.
Mobile apps
Applications developed for environments where bandwidth usage matters (smartphones, smartwatches, IoT devices) would make the best of what GraphQL offers.
Conclusion
APIs are key components of modern software infrastructure, and choosing an approach for developing them depends on several factors, including the project requirements, the preferences and experience of developers, and many more.
REST vs GraphQL? While REST is considered a conventional architectural pattern for API development, GraphQL represents a modern tool with its features over REST and a vast, fast-growing community.
However, these two technologies don’t conflict - they can co-exist and be used simultaneously.
We, at Axon, specialize in both approaches and are open to discussing which one fits best for your project!