GraphQL vs REST

GraphQL vs REST

Image for post

REST has been adopted by many developers and is widely regarded as the traditional way to send data over HTTP. GraphQL, on the other hand, is typically presented as a revolutionary technology to replace legacy REST APIs.

The question is: How do both API design architectures stack up against each other?

In this article, we?ll dig deeper to learn about the similarities and differences between GraphQL vs REST and walk through some practical examples to help you better understand both technologies.

REST: What It Is, Benefits, and Limitations

REST is an API design architecture that?s used to implement web services. RESTful web services allow systems to access and manipulate the textual representations of web resources using a predefined set of stateless operations (including GET, POST, PUT, and DELETE).

What?s more, is that the implementation of the client and server is often done independently. This means that client-side code can be changed without affecting how the server operates and vice versa. In this way, they?re kept modular and separate.

The core idea of REST is that everything is a resource that?s identified by a URL. In its simplest form, you would retrieve a resource by putting through a GET request to the resource?s URL and get a JSON response (or something similar depending on the API).

It might look something like this:

GET /movies/1

It?s important to note that with REST, the type (or shape) of the resource and the way you fetch that particular resource are coupled. So, you might refer to the snippet above as the movie endpoint.

Benefits of REST

One of the key advantages of REST is that REST is scalable. The architecture decouples client and server which allows developers to scale products and applications indefinitely without much difficulty.

In addition to this, REST APIs offer a great deal of flexibility. Practically speaking, since data isn?t tied to resources or methods, REST is able to handle different types of calls and return different data formats. This allows developers to build APIs that meet the user?s specific needs while being mindful of the needs of a diverse user base.

Limitations of REST

Most web and mobile applications developed today require large sets of data that typically combine related resources. The problem is that accessing all of that data to get everything you need using a REST-based API requires multiple round trips. For example, if you wanted to retrieve data from two different endpoints, you?d have to send two separate requests to the REST API.

Another common problem developers face with REST is over- and under-fetching. This is because clients can only request data by hitting endpoints that return fixed data structures. Due to this, they aren?t able to get exactly what they need and run into either an over-fetch or an under-fetch scenario.

  • Over-fetching is when the client downloads more information than what the application actually needs.
  • Under-fetching is when the endpoint doesn?t provide all of the required information so the client has to make multiple requests to get everything the application needs.

For example, let?s say you?re working on a screen for an app that needs to display a list of users with their names and birthdays. The app would hit the /members endpoint and, in turn, receive a JSON data structure with the user data. However, the data structure would contain more information about the users than what?s required by the app. For example, it might return the user?s name, birthday, email address, and phone number.

GraphQL: What It Is, Benefits, and Limitations

GraphQL is an API design architecture that takes a different, more flexible approach. The key difference between GraphQL vs REST is that GraphQL doesn?t deal with dedicated resources. Instead, everything is regarded as a graph implying it?s connected.

What this means in practical terms is that you can tailor your request to match your exact requirements using the GraphQL query language. In addition to this, it lets you combine different entities into a single query.

A GraphQL query for a movie listings app might look something like this:

Benefits of GraphQL

Every time you modify your application?s UI, there?s a pretty good chance that your data requirements will also change i.e. you?ll either need to fetch more data or less data than before. GraphQL makes rapid product iterations on the front-end possible as it allows developers to make changes on the client-side without messing around with the server.

Additionally, with GraphQL, developers are able to gain insight into the data that?s requested on the back-end and how the available data is being used. This is because, with GraphQL, each client specifies exactly what information they need. This way, developers are able to deprecate fields that clients no longer use in order to improve API performance.

GraphQL defines the capabilities of APIs using a strong type system that essentially tells the client how it can access data. The key benefit of this schema is that both front-end and back-end teams know the structure of the data and can, therefore, work independently.

Limitations of GraphQL

The major downside of GraphQL is that it uses a single endpoint instead of following the HTTP specification for caching. Caching at the network level is important as it can reduce the amount of traffic to a server or keep data that?s accessed frequently close to the client via CDN.

Additionally, it?s not the best solution for simple applications as it adds complexity ? with types, queries, resolvers ? to things that could be done much simpler with REST.

Let?s step through a practical example to compare GraphQL vs REST and see the similarities and differences of both API design architectures.

Practical Example of GraphQL vs REST

Let?s say you have an online store and you?d like to showcase your latest products in a product catalog on your website. The first step would be to fetch the products:

GET /api/products

Now let?s say later down the line you wanted to display the product?s delivery options and expected delivery time in the product catalog. You?d have three options, each with their own problems:

Option #1: Fetch the product SKUs from another resource

GET /api/products/:id

Problem: Following this approach, you?ll run into an under-fetching scenario. To display the delivery information, you?d now have to run two server requests instead of a single one. And if your requirements change in the future, performance would take a hit.

GraphQL Solution: With GraphQL, you would only run a single query instead of making multiple round trips. Here?s how:

Option #2: Modify the existing resource to also return product SKUs

GET /api/products

Problem: At first glance, this might seem like a neat solution. However, if you?re displaying product listings elsewhere on your online store ? such as in widgets ? then you?d be over-fetching data.

GraphQL Solution: With GraphQL, clients are able to fetch only the data they need, nothing more. So, a simple ?

? the query would prevent over-fetching.

Option #3: Create a new resource that returns the original product details along with the product SKUs

GET /api/productsWithDeliveryDetails

Problem: The main problem with this approach is that you?d have to define a new endpoint for each view you need to display on the front-end. This slows down front-end development and makes it difficult to update the UI.

GraphQL Solution: With GraphQL, clients are able to fetch exactly what they need so going back and making front-end updates won?t be a problem. In fact, all you?d have to do is add a new field to the query.

Similarities and Differences

GraphQL and REST are similar in a few ways. More specifically:

  • Both are based on the concept of a resource and can specify IDs for resources.
  • Both can be fetched via an HTTP request.
  • Both can return JSON data in the request.

And here are some of the ways GraphQL and REST are different:

  • Data fetching with REST causes over- and under-fetching issues whereas this simply isn?t possible with GraphQL.
  • The endpoint you call in REST is that object?s identity whereas, in GraphQL, the object?s identity has nothing to do with how you fetch it. In other words, in REST you define the object on Backend and on GraphQL you “define” this object on Frontend.
  • With REST, the server determines the shape and size of the resource whereas, in GraphQL, the server simply declares the available resources and the client can ask for exactly what it needs.
  • REST automatically puts caching into effect whereas GraphQL has no automatic caching system.
  • Error handling in REST is much simpler as compared to GraphQL which typically gives you a 200 OK status code.

Comparing GraphQL vs REST using Back4App

Back4app is a great place to compare REST and GraphQL because it supports both out of the box and automatically creates everything that you will need.To illustrate that, let?s create a class called Person, with two properties: name (string) and age (number).Make sure you are using Parse 3.5.0 or above so GraphQL support can be automatically set.

Add a few objects to that class by clicking the ?Add a Row? button.

Image for post

At this point, you might have noticed that you did not need to code anything. You created your class, set its properties, saved objects and now have a fully working API that supports REST and GraphQL and can insert, delete, update, and search for objects.It is fully scalable, secure and will automatically update methods to reflect any database changes that you do in the future.

Also, for GraphQL queries and mutations, the platform will automatically create documentation for Queries and Mutations and generate Schema files that you can integrate into your projects:

Image for postGraphQL DocsImage for postGraphQL Schema

Now that our class and objects are set, we can start comparing both ways to query.First, let?s try the REST.

Image for postREST API Console at Back4App.com

Notice that in the results object, both name and age were retrieved by the platform. If our intent was just to retrieved the name property we just had an over-query situation, resulting in a bigger payload and more data traffic consumption.

Let?s try that with GraphQL now and see how it behaves.

Image for postGraphQL API Console at Back4App.com

For that query, we also retrieved name and age, but this time I had to specifically tell the platform the properties I was looking for:

If I only needed the name, I could change that to

and avoid the over-query, resulting in a smaller payload, which response faster and potentially saves up on data traffic.

With those results we can conclude that though we had similar results, GraphQL allows for a more maintainable way to evolve the API over time, allowing for changing the queries as needed to retrieve only the information we need, at the time we need.

As it by-design mandates that we specify the information we want to retrieve, there is no way to over-query unless the programmer intentionally does so.

By testing both approaches you can pick the one that best fit your needs, or even if a mix of both depending on your goals, as both are automatically created and automatically reflect database changes over time. Both are and will ever be available.

Be sure to check out the Back4Press API Documentation to learn how to connect your app to Back4App and utilize the back-end resources it offers.

Conclusion

GraphQL and REST are simply two ways to send data over HTTP. While GraphQL certainly has many advantages over REST, it?s not always the best implementation. We encourage you to sign up with Back4App and try it out for yourself!

What?s your experience been like with GraphQL vs REST? Let us know in the comments section below.

Create your account at Back4App.com and test which approach is best for your application.

16