STAR US

GraphQL vs REST: Differences, Similarities, and Why to Use Them

Contents

Modern applications allow us to get connected to the world like never before. However, how is this structure so effective in providing a robust connection between different applications and data sharing between different devices? API (Application Programming Interface) allows developers to build complex features and expose application functionalities as resources.

The purpose of an API is to communicate between the client and the server. This includes the processes of data transfers, data security, and distribution to different networks and third-party applications. The beauty of APIs is that anyone can access information and features that would otherwise be unobtainable without the need to provide any custom code or integrations.

As a developer, there are different protocols and architectures that you can use to create API services and consume resources. This include:

  • REST
  • RPC
  • GraphQL
  • SOAP

Let's learn how GraphQL compared with REST.

What is GraphQL

GraphQL is a query language for APIs used to communicate data between a client and a server. GraphQL is usually defined using schema to query data from a server or mutate data remotely. GraphQL provides strongly typed tooling for your server. When working with GraphQL, as a front-end developer, you'll always know the exact shape of the data you're expecting back from the server. This allows you to structure data-driven applications much more flexibly and efficiently than the REST AND SOAP approach.

With GraphQL, the data in your API is completely and clearly described. It allows clients the ability to request only what they require. As a result, it is simpler to stretch APIs over time as well as robust developer tools are made possible. Additionally, it gives app developers better flexibility over how data is used in their applications.

What is REST

REST stands for REpresentational State transfer. It defines how communication should happen over HTTP. The REST architecture exposes resources with its own unique URI (Uniform Resource Identifier)(Endpoints). Clients use this endpoint to access the server by sending a request. Each endpoint is executed based on HTTP methods such as GET, POST, PUT, DELETE, and PATCH. This way, each resource to the server is consumed using a single endpoint that executes a single HTTP method.

Let's check out a basic example to understand how these two work.

GraphQL vs REST: A practical example

REST is one of the oldest and most popular approaches to creating API. However, there is a big difference between GraphQL and REST architecture and how each implements an API. Let's learn the high levels of differences between these two approaches.

Take a basic example of a social media application that displays user information, the posts of that user, and the follower associated with that user.

When using a REST architecture, you will be required to have three different endpoints (URL), each with a request type to fetch these resources. Here is a presentation of these URLs:

Data Fetching with REST

Image Source

When using the GraphQL approach, the client will only need to send a single request using only one endpoint to get the same data you would actually use three endpoints and send different requests to get these data. Here is a basic example:

Data Fetching with GraphQL

Image Source

When using GraphQL, the client will only query the data needed. In the REST example above, each request will fetch every data associated with that single endpoint. For example, to return a user, the endpoint /users/<id> will return the data as follows.

Image Source

Let's assume you want only to get the follower's name. A GraphQL API will come in handy in such a scenario.

-----------------------------------------------------
Request1:       | Response1:

query {         | {
 User (id: 1) { | "User": {
    id          | "id": 1
    name        | "name": "Mary"
 }              |     }
}               | }
-----------------------------------------------------

And you can still add more parameters based on the exact data you want

-----------------------------------------------------
Request2:       | Response2:

query {         | {
 User (id: 1) { | "User": {
    id          | "id": 1
    name        | "name": "Mary"
    birthday    | "birthday":  "July 26, 1982"
 }              |     }
}               | }
-----------------------------------------------------

The Differences Between GraphQL and REST

Now that we understand these two approaches. Let's dive deep to find out the differences that exist between them.

Operation

Based on the definitions we have derived above, REST has different operations, these are, CREATE, READ, UPDATE and DELETE. Each of these operations is executed using an HTTP method. They include GET, POST, PUT and DELETE. Each resource in the API is accessed using a respective endpoint. To a REST API, you need controllers that map each HTTP method to its respective operation as well as provide URI for each and every API Endpoint.

On the contrary, GraphQL does not require controllers to manage HTTP methods. In terms of its operation, it uses a query mutation subscription approach. This way, GraphQL will only have one endpoint. All API calls will go to that endpoint for every operation you have inside your GraphQL application. Therefore, you don't need controllers to manage HTTP method mapping. The single endpoint will be enough to manage your API operations.

API Organization

While REST uses Endpoints to access the API resources, GraphQL has a schema and type system. You need to provide a schema to access different fields. With GraphQL you need to that pass the fields want in the response using a schema that follows a GraphQL-type system. This increases the stability of the API as the type system provides automatic error checking and validation.

API Response

A REST API has a fixed expected API response. Let's say you are exposing 20 fields to your clients. Every request will return the 10 fields in the response. Likewise, every client will get 10 fields in the response for that particular API. However, the GraphQL API offers the flexibility to modify the sent request and ensure the client only gets the exact fields. That means the different consumers can ask different fields in the response and adhere to only what that specific client wants for the same operation.

Over and Under Fetching

Based on the API Response, a REST-based API can result in either over-fetching or under-fetching. It has a fixed response. If the client wants to get 10 fields in a list of 30 fields, REST can't simplify that. This will result in over fetching of an extra 20 fields in the response which the client doesn't need. In other scenarios, if let's say a user is sending a get request to fetch the first name and last name based on the user ID. This can result in under-fetching if the API only exposes the first name to the client. GraphQL However, due to its response flexibility, it eliminates API over and under fetching.

When to use GraphQL or REST

These two ways of creating APIs are best when used on their strength. Let’s discuss some use cases that best fit each approach.

The GraphQL

  • GraphQL best fits when used with nested data. For example, using the practical example explained above, GraphQL will work best when fetching comments associated with every given post. This makes it best when used alongside Enterprises' data sources, such as let’s say New York times.
  • Due to its ability to control over-fetching, GraphQL is great when you have limited bandwidth, such as when using mobile devices and smartwatches.
  • GraphQL shines most when used to handle microservices. GraphQL works fine when consuming and fetching data from different sources that require a microservice architecture.
  • Due to its response flexibility, GraphQL is a good choice when working with data that can’t predict when the API will be used by the client. This goes hand in hand with when you want to make your API public. A client can use the API you fetch different resources that you can predict.

The REST Approach

  • When creating a simple API intended to only serve one client, and you don’t need to worry about bandwidth performances, or the multiple rounds to fetch data, REST should be a good choice.
  • Since REST has different HTTP methods that predetermine the operation from the client, you can use it to control the endpoints that a given client can access based on the operations that a given client can perform.
  • If you need a well-designed API use case, REST is a good choice. It will allow you to restrict data based on its different HTTP methods.
  • REST uses the HTTP method, which makes the implementation predictable for the client. REST shines most when you have a specific data structure.
  • REST works great if you want to cache requests. REST uses different endpoints that make caching seamless. GraphQL uses a single endpoint and a custom request, and that can be challenging to implement caching technologies out of the box
  • GraphQL only exposed data using JSON format. If you need to expose your data using other methods, such as XML and HTML, REST is great for doing exactly that.

Based on the above use case, it doesn’t mean GraphQL or REST can't work in a given situation. This only explains when each approach shines the most.

REST in Memphis.dev

What is Memphis.dev?

Memphis is a next-generation message broker.

A simple, robust, and durable cloud-native message broker wrapped with an entire ecosystem that enables fast and reliable development of next-generation event-driven use cases.

Memphis requires zero ops, enables rapid development, extreme cost reduction, eliminates coding barriers, and saves a great amount of dev time for data-oriented developers and data engineers.

Memphis focuses on four pillars

  1. Stability - Queues and brokers play a critical part in the modern application's structure and should be highly available and stable as possible.
  2. Performance and Efficiency - Provide good performance while maintaining efficient resource consumption.
  3. Observability - Reduces troubleshooting time to near zero.
  4. Developer Experience - Rapid Development, Modularity, inline processing, Schema management.

To enable message production via REST for various use cases and ease of use, Memphis added a REST gateway to receive messages via HTTP.

Popular use cases produce events directly from a browser, user session, frontend, and receiving data through 3rd party apps.

GraphQL in Memphis.dev

Data pipelines are constantly breaking and creating data quality issues, usability issues, and there is a communication chasm between service implementers, data engineers, and data consumers.

By defining a well-structured schema and enforcing it over your different data producers, you increase the quality of your data, lower the client logic needed to transform unstructured data, and decrease pipelines and consumer breaks.

Memphis Schemaverse was created to provide a robust schema store and schema management layer on top of memphis broker without a standalone compute or dedicated resources. With a unique and modern UI and programmatic approach, technical and non-technical users can create and define different schemas, attach the schema to multiple stations and choose if the schema should be enforced or not. Memphis' low-code approach removes the serialization part as it is embedded within the producer library. Schema X supports versioning, GitOps methodologies, and schema evolution. Schemaverse supports Protobuf, JSON, and GraphQL.

Conclusion

GraphQL uses a graph to represent objects to query data. Unlike REST, GraphQL uses a single endpoint to access different resources from the server. Its graph-like representation allows you only to query the data that the client wants and any given point.

I hope this example helped get the main difference between the classical REST and the GraphQL approach.

Related Articles

share:

We will keep you updated

It's all about data engineering and dev practical materials

We will keep you updated

It's all about data engineering and dev practical materials