REST VS GRAPHQL: The Unmasking

REST VS GRAPHQL: The Unmasking

APIs have been an essential component of software development for decades. Application Programming Interfaces (APIs) enable communication between different software pieces by serving as an intermediary that dictates how data should flow from one component to another.

Picture this: you want to surprise your friend, Thomas, by taking him to lunch. You arrive at his office and approach the Receptionist to ask if Thomas is around, and kindly ask the Receptionist to inform him about your visit. The Receptionist then calls Thomas and tells you to go up to room 15 on the 3rd floor after talking to him. In this scenario, the Receptionist can be likened to an API because he/she serves as a medium for you to communicate with the other party, Thomas.

APIs come in different forms and these forms are termed API architectures. An API architecture defines the set of rules and structures that an API must follow. Numerous API architectures are currently used in the industry, with the common ones being REST, GraphQL, gRPC, SOAP, Websockets, Webhooks, etc. In this write-up, we will focus on REST and GraphQL. We will look at what makes them unique, together with some pros and cons of using them. Let’s start with the more popular architecture between the two, REST.

REST

REST, which stands for Representational State Transfer, is the most widely used API architecture in the industry. REST APIs utilize HTTP to convey information in JSON, XML, or even plain-text formats.

Introduced in 2000, REST has dominated the world of APIs due to its convenience and minimal learning curve. REST is characterized by several features, including statelessness, which ensures that each client request must contain all the necessary information required to fulfil that request and that the server, in adherence to this principle, should not store user information between requests.

Anytime you think of REST, think of resources. Bear in mind that resources can be anything ranging from basic data objects to sophisticated services.

Visual illustration of REST

Visual illustration of REST

Notably, one constraint of REST API is HATEOAS (Hypermedia As The Engine Of Application State). In simpler terms, HATEOAS allows clients to navigate an API using only the links provided in the API's response, instead of relying solely on other forms of documentation or third-party tools such as OpenAPI.

{
    "userId": 10,
    "username": "johndoe",
    "createdAt": "2023-11-12T08:30:00Z",
    "_links": {
        "self": {
            "href": "http://api.example.com/users/10"
        },
        "posts": {
            "href": "http://api.example.com/users/10/posts"
        },
        "comments": {
            "href": "http://api.example.com/users/10/comments"
        }
    }
}
Sample of a REST API response with HATEOAS implementation

Now, let’s delve into some pros and cons of REST APIs.

PROS OF REST

  • Decoupled server and clients: This is because the client and server implementations are kept independent of each other.

  • Minimal learning curve: REST APIs have a minimal learning curve because it is simple to understand and use. Even your grandpa could master them.

  • Easier implementation of caching: REST APIs allow for responses to be cached effortlessly, thereby enhancing application performance.

CONS OF REST

  • Over-fetching: This occurs when an API usually returns a plethora of data that may not be used by the client.

  • Under-fetching: On the other hand, under-fetching occurs when REST APIs provide insufficient data. This would require making additional client requests to the server.

  • Documentation: REST APIs often require more detailed documentation than other API architectures such as GraphQL.

While REST is widely used, it is extremely optimal in scenarios that require a resource-centric approach. A good understanding of when to leverage REST is crucial for effectively harnessing its benefits.

GRAPHQL

GraphQL, which stands for Graph Query Language, was developed by Facebook in 2012. It was created to primarily solve the “Over-fetching and Under-fetching” pitfall of REST APIs. At its core, GraphQL is a query language that allows developers to fetch only data that is useful from the server. It is seen as a successor to REST APIs because of its benefits.

Unlike REST, GraphQL requests data with queries. Let’s try to get a better understanding of GraphQL using our favourite “Picture this” scenario. Now imagine you are planning a surprise birthday party for our friend, Thomas, and for the sake of familiarity, let's stick with the Receptionist from the previous scenario. You need multiple pieces of information from the Receptionist like what Thomas’ workday looks like: his meetings for the day; when he closes from work; his favourite colleagues from the office; and other relevant details. Instead of making multiple enquiries, you submit a single request with all the information you need at once. This time around, the Receptionist gathers all the required details from the intended source(s) and presents them in one structured response.

Here, the Receptionist is the GraphQL endpoint, that processes a single query and fetches the relevant information from various sources including Thomas’ calendar and other shared channels. GraphQL, just like the receptionist, saves time and is highly performant.

Visual illustration of GraphQL

ESSENTIALS OF GRAPHQL

GraphQL has some essentials that should be noted. Some of them are as follows:

  • GraphQL utilizes Resolvers to fetch the requested data from the server.

  • GraphQL supports real-time data updates through the use of subscriptions. Here, the server pushes updates to the client when the said client subscribes to specific events (e.g. when a user is added).

  • Unlike REST, GraphQL provides a single endpoint (e.g. ‘.../graphql’) and enforces its structure through a schema that defines the available data types and their formats.

Talking of GraphQL Schema, it incorporates various elements including:

  • Queries: these specify how clients can request data from the server, similar to GET requests in REST APIs.

  • Mutations: these define how clients can modify data on the server side. Think of mutations as operations like POST, PUT, PATCH, and DELETE but in a GraphQL context.

  • Subscriptions: As previously described.

  • Types: they represent the data structures used in GraphQL, encompassing object types, scalar types, enum types, and more.

  • Scalars: they represent primitive data types such as Int, Boolean, String, and ID. They can also include other custom scalar types (e.g. BigDecimal).

  • Other crucial elements include Fields, Enums, Interfaces, etc.

# This is a GraphQL query to fetch user information
query {
  user(id: 10) {
    username
    createdAt
    posts {
      title
      content
    }
  }
}
# This is a GraphQL mutation to create a new user
mutation {
  createUser(input: {
    username: "johndoe",
    email: "johndoe@example.com"
  }) {
    id
    username
    email
    createdAt
  }
}
# This is a GraphQL subscription to receive notifications about new posts
subscription {
  newPost {
    title
    content
    author {
      username
    }
  }
}

Just like other technologies, GraphQL has a fair share of pros and cons. Below are some of them:

PROS OF GRAPHQL

  • GraphQL does not require developers to incorporate explicit documentation because documentation is automatically generated and is always up-to-date. This makes development faster than usual.

  • GraphQL allows clients to request data with precision, eliminating the issues of over-fetching and under-fetching.

  • It supports the consolidation of multiple requests into a single request, minimizing the overhead associated with making numerous API calls.

  • GraphQL employs a strongly typed data structure, making it easier to catch errors early in the development process.

CONS OF GRAPHQL

  • GraphQL has a steep learning curve, resulting in a smaller community compared to that of REST.

  • Implementing caching in GraphQL is more challenging compared to REST.

  • GraphQL can present performance challenges with complex queries. GraphQL’s flexibility enables clients to create complex queries, but this freedom can give rise to performance challenges. Poorly managed or unoptimized queries may result in these performance issues.

  • Another concern with GraphQL is Query Depth, where queries refer to objects recursively. Malicious users could create a query payload that imposes a substantial load on the server, potentially resulting in a server crash.

PERSONAL INSIGHT

With experience in both REST and GraphQL, I have found REST to be my go-to in many scenarios, especially with projects that are under tight deadlines and limited team resources. However, one thing I enjoy the most about using GraphQL is the automatic generation of documentation, which tends to save me valuable time to focus on other aspects of development. In my opinion, each technology has its place.

Ultimately, the selection of API technology depends on various factors, such as project requirements, and the adaptability of your team. GraphQL is well-suited for certain use cases, some of which include real-time applications (that can utilize GraphQL’s subscriptions) and applications that aggregate data from various sources. On the other hand, REST is ideal in scenarios where a project requires a resource-focused approach. Additionally, REST is commonly chosen for its wide adoption and simplicity.

If you are reading this write-up, you have likely used REST before. But have you tried GraphQL? Let me know your thoughts on both technologies.