Exploring the power of GraphQL with REST and the Future of API development

Exploring the power of GraphQL with REST and the Future of API development

Introduction

Suppose you are a child and your mother asks you to bring some bread from the nearby grocery store. So you just go and buy a packet of bread and come back. After you return, your mother told you to buy some vegetables from the vegetable shop because she forgot to tell you before about them. You get annoyed and you agree to go anyways. You may think that wouldn't it be nice if you had a supermarket near you where everything was available all at once. The former scenario of different shops and going to each shop separately can be imagined as REST API and the latter supermarket can be identified as GraphQL. Let's learn more about GraphQL in this blog!

GraphQL is a query language for reading and mutating data in APIs. graphql.org defines it as:

GraphQL is a query language for your API, and a server-side runtime for executing queries using a type system you define for your data.

This blog focuses on basic understanding, advantages, some disadvantages that people don't discuss much and when to use GraphQL.

You might think- "I already use REST API, why should I switch to GraphQL?" or "How does GraphQL improve upon those drawbacks?". To answer questions like these, I will take an example of API implementation on an e-commerce website.

Drawbacks of REST:

  1. We may need multiple entities at once. In this scenario, each request is under-fetching the actual data we want. We visit multiple URLs like /product and /seller one by one if we want both results.

    REST handles requests sequentially, which can make it slower for applications that need to make many requests simultaneously.

  2. We may need only a small subset of a data entity. In this case, we still over-fetch the results from the REST API. We may need the product with id=2 and we are still fetching this lengthy JSON object with REST. This may look small but for a big e-commerce platform, it can go for hundreds and thousands of lines.

     {
       "products": [
         {
           "id": 1,
           "name": "Laptop",
           "price": 2000,
           "sellerId": 1
         },
         {
           "id": 2,
           "name": "Smartphone",
           "price": 500,
           "sellerId": 2
         }
       ],
       "sellers": [
         {
           "id": 1,
           "name": "Ayush Gupta",
           "age": 21
         },
         {
           "id": 2,
           "name": "Lorem Ipsum",
           "age": 34
         }
       ]
     }
    
  3. REST API has inflexible endpoints which can lead to additional complexity on the client side.

    • Suppose the website has a REST API with the following endpoints:

      • /products: Returns a list of all products available for purchase on the website.

      • /products/:id: Returns a single product with the specified ID. If a user wants to display all the products on the website, the user would need to make a request to /products . If that person wants a product with a specific id, they would need to make a request to /products/:id . This will require multiple requests and in turn, this will cost the website its efficiency.

  4. If the REST API does not have extensive documentation, then it is difficult to understand it.

GraphQL to the rescue!

  1. Instead of multiple URLs, a GraphQL API has a single entry point. The model is as follows:

    If we take the same example of e-commerce then it can be shown as follows:

    GraphQL's ability to batch requests can make it a more efficient choice. Batching involves collecting multiple requests and combining them into a single request. It is often implemented with a timing threshold. For example, a client might wait 100ms before making a query if it receives a request from a component. If any other queries are requested within that 100ms window, all of those additional queries are sent at the same time, instead of separately. This can be an effective way to improve the performance of a GraphQL API by reducing the number of network requests.

  2. Data is fetched by describing it with a syntax that mirrors its return structure in JSON. the sample schema.graphql file below:

     type Seller{
         id: ID!
         name: String
         age: Int
         products: [Product]
     }
    
     type Product{
         id: ID!
         name: String
         price: Int
         seller: Seller
     }
    
     type Query{
         products: [Product]
         seller( id : String!): Creator
     }
    
     type Mutation{
         getProduct(id:String) : Product
     }
     // Mutation <=> Manipulate Data (POST, PATCH, DELETE and PUT)
     // Mutations are GraphQL's way of applying data manipulation to resources
    

    From here, we can write code to resolve this data in other programming languages. You can learn more about schemas from the official documentation.

  3. GraphQL has flexible endpoints. Example is:

     query {
       product(id: "1") {
         name
         category
       }
     }
    

    In this example, the GraphQL server will return only the name and category fields for the user with an id of "123". The server then responds with only the requested data because the endpoint is flexible and it can return different data depending on the query provided. The data can be imagined as follows (where product and sellers are nodes of a graph and connected products have the same category):

  4. GraphQL provides a self-documenting API which allows developers to easily understand and use the API.

  5. Has features like subscriptions. Subscriptions are GraphQL's way for clients to receive notifications on data modification.

As everything has some disadvantages, GraphQL has its disadvantages too.

Drawbacks of GraphQL:

  1. With REST API, we don't need a special library to consume API. Whereas, GraphQL requires additional support both on the client and server side. Some of the support includes:

    • graphql.js: reference implementation of GraphQL in javascript. It can be used with Express

    • Apollo server: a famous open-source GraphQL server.

    • GraphQL client libraries to work on frontend

  2. Difficult to cache: GET request used in REST API has a properly defined caching behaviour by many browsers and web servers. GraphQL has a single point of entry and uses HTTP POST by default which is hard to cache.

  3. Security is difficult to implement in GraphQL.

    • GraphQL requires a creative way of thinking about authorization because basically, GraphQL is flipping the control of what data is returned to the client.

    • With REST API, you know what piece of data you're going to return. If you know this, you can optimise the security and authorization check in a central space. In GraphQL, you can fetch any piece of data from wherever which means that authorization checks need to be closely tied to the data fetching of GraphQL.

When to use GraphQL?

  • You can use GraphQL if you are building a frontend heavy application and you need to iterate fast and you need to build things quickly on the frontend and you have JSON data.

  • if you have file or video data then GraphQL is not a better fit.

  • GraphQL is not recommended in microservice to microservice communication. (In that case, developers usually prefer gRPC)

  • GraphQL can be used in the building of quick and responsive mobile applications.

Why not use the best of both worlds?

Despite their differences, both GraphQL and REST APIs have a role to play in the future of API development. GraphQL can address some of the limitations of REST APIs, such as over-fetching and inflexibility, and REST APIs can provide a solid and convention-based approach that can be beneficial in certain situations. Ultimately, the choice between GraphQL and REST APIs will depend on the specific needs and requirements of the project. Both technologies have their strengths and can be useful in the right context.

Hybrid approaches combining REST and GraphQL can offer the advantages of both technologies and allow developers to select the best solution for each use case. For instance, a hybrid approach could use a REST API for endpoints that need a solid, convention-based approach, and a GraphQL API for endpoints that need more flexibility and the ability to specify exactly which data is needed. This enables developers to use the strengths of both technologies and choose the best solution for each endpoint.

Another option is to use GraphQL as a layer on top of a REST API, where the GraphQL server sits between the client and the REST API and translates GraphQL queries and mutations into REST API calls. This provides the benefits of GraphQL, such as flexibility and the ability to specify exactly which data is needed, while still using a REST API to access the underlying data. In general, hybrid approaches combining REST and GraphQL can offer the advantages of both technologies and allow developers to select the best solution for each use case.

Conclusion

In my opinion, if we talk about the future, both REST and GraphQL are here to stay. We just need to find out what seems fit for our application. We can always try the hybrid approach to work with the strengths of both technologies. Learning to work with both can be fruitful for developers in improving the overall efficiency while developing the app.