DEV Community

Cover image for Is GraphQL better option than Rest ?
Arpan Bandyopadhyay
Arpan Bandyopadhyay

Posted on

Is GraphQL better option than Rest ?

GraphQL is great if you want to work in a declarative approach because it enables you to select only the information you need. You need to choose it by depending on your use case for your project. For some user case Rest is a great fit , also for some use case you can see GraphQL will play well .

Here I am discussing when you need to choose what in terms of use case one by one :

If you are planning to use GraphQL, in below situations, you should use it without thinking twice :

DEVELOPING MOBILE APPS
It would be best to use GraphQL when you are designing UI/UX rich applications for smartphones, smartwatches and IoT devices. GraphQL can help in loading content that the user actually needs and preserving the user experience under slow network speeds.

WHEN YOU HAVE TO HANDLE COMPLEX SCHEMA
GraphQL can assist in managing the complex schemas. If your application is based on numerous schemas that use multiple nested models and associations, you should go with GraphQL. REST is very weak in this section if you are likely to come in contact with complex queries. Being a query language, GraphQL can access the nested objects easily with a single API request and return structured data correctly tagged along with JSON.

As an example:

Assume I have two database tables:

  1. *Employee *- Having follwing columns - name, id (PK), email, mobile ,city , deptid(FK references deptid of Department table)
  2. *Department *- Having follwing columns - deptname, deptid(PK)

Now

"I want to fetch Employee name associated with HR department"

If I use Rest then I have to write Join query . But in case of GraphQL I can directly query the employee name like below with one single endpoint

query{
  searchDeptByName(deptName:"HR"){
    employee{
      employeeName****
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

and I will get Response like below :

{
  "data": {
    "searchDeptByName": {
      "employee": [
        {
          "employeeName": "Arya"
        },
        {
          "employeeName": "Tushar"
        },
        {
          "employeeName": "Rekha"
        },
        {
          "employeeName": "Roshan"
        }
      ]
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

This way GraphQL simplifies managing complex schema (Though above is not too complex but in real time we can have more complex schema)

WHEN YOU WANT TO TO HIDE BACKEND COMPLEXITIES
GraphQL has two prominent features that make it a perfect situation for microservice orchestration.
• The first feature lets you abstract your RESTful API and create a unified and fully optimized public API for your microservices. The benefit of this feature is that you can handle future versions of your API smoothly.
• The second feature deals with the situation when you are creating a single GraphQL schema by stitching schemas together from multiple underlying GraphQL APIs.
These both features help in hiding code complexities from the clients.

BETTER DEVELOPING EXPERIENCE
The best scenario to use GraphQL is when you want to provide a better experience to your developers. With the descriptive language to handle complex queries, the capability to simplify the loading of state management and facility to manipulate types instead of tweaking with JSON data.

WHEN YOUR APPLICATION RECEIVE DATA FROM MULTIPLE RESOURCES
GraphQL exposes a single endpoint that allows you to access multiple resources. Also, resources are not exposed according to the views that you have inside your app. So if your UI changes — i.e., requires either more or less data — it doesn’t have an impact or require changes on the server.

Image description

Now you should drop your idea to use GraphQL in the following situations.

WHEN YOU ALREADY HAVE REST
GraphQL is an effective alternative to REST, so if you are acquainted with REST, why to settle for replacement? The primary feature of GraphQL is to send a query specified with the exact information that you need. But, this can be easily achieved using REST – from passing the name of the field to utilizing it in the URL. On top, there are a lot of JSON libraries available that can help you in implementing and supporting this specification.

WHEN YOU WANT TO USE WEB CACHE
Implementing a web cache at the database level or the client level with in-memory cache implementation can be an easy task. A cache implementation at the HTTP level with a reverse proxy server that stores the content of a request – can reduce the amount of traffic that reaches a server. Since a REST offers numerous endpoints, which facilitates to configure web-cache to a URL easily.

WHEN PERFORMANCE IS YOUR PRIORITY
GraphQL gives the power to execute queries to get the exact results. But, if a client sends a query for numerous fields and resources, you might face a performance issue. For complex queries, GraphQL must be designed very carefully, and you can’t just put it over the REST API or database. You have to define each endpoint and tune queries to retrieve specific data. All this designing and defining can affect the performance of the API.

As an example :

Give me the information about the users that posted a review for all the books of this author

author(id: '1234') {
  id
  name
  books {
    id
    title
    reviews {
      text
      date
      user {
        id
        name
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

You can simply let your users run any query they want. A GraphQL API must be carefully designed; it’s not just about putting it on top of a REST API or a database.

For complex queries, a REST API might be easier to design because you can establish multiple endpoints for specific needs, and for each, you can fine-tune specific queries to retrieve the data in an efficient way.

This might be a bit controversial because multiple network calls can also take a lot of time. But if you’re not careful, a few big queries can bring your server down. In that sense, GraphQL’s greatest strength can also be its greatest weakness.

REST is better for error handling and tooling
Error handling in REST is easier when compared to GraphQL. RESTful APIs follow the HTTP spec with regards to resources
and returns various HTTP statues for various API request states. GraphQL, on the other hand, returns the 200 Ok status for every API request, including for errors. This makes it difficult to manage errors and makes it hard to integrate with monitoring tools.

Now coming back to security.
Is GraphQL less secured than Rest?

No not at all!!
GraphQL is a very powerful query language that does a great many things right. When implemented properly, GraphQL offers an extremely elegant methodology for data retrieval, more backend stability, and increased query efficiency.

The key here though is that simple phrase — when implemented properly.

There are many ways to secure GraphQL query:

1. Authentication
Authentication is determining whether a given user is logged in and subsequently remembering who they are. Authentication can provide context to a session and personalize the type of data that a user sees.

2. Authorization
Authorization is then determining what a given user has permission to do or see. In GraphQL, we’d use this to manage access to particular queries and mutations based on identity, role, or permissions.

To implement authentication & authorization we can make use of Spring security with Oauth2/JWT . There are many other tools which can be used. If we deploy our application to Google Cloud we can make use of Apigee as an API gateway to perform authentication , authorization .

3. Limit query depth
GraphQL gives clients the ability to ask for data in a variety of different ways. Because of the various entry-points ava

ilable to request data, it’s possible to write exceptionally large nested queries like the following.

query{
  searchDeptByName(deptName:"HR"){
    employee{
      employeeName
      department{
        deptName
        employee{
          employeeName
          department{
            deptName
            employee{
              employeeName
              # and so on
            }
          }
        }
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Queries like this are dangerous because they’re expensive to compute. They could crash our API and take up all available resources.

We can specify the max depth across your queries to mitigate this problem by added below propertiy in Spring application.properties

graphql.servlet.maxQueryDepth= 3 # Here 3 is max Query depth

Now If we execute the above query we will get error:

{
  "errors": [
    {
      "message": "maximum query depth exceeded 7 > 3",
      "extensions": {
        "classification": "ExecutionAborted"
      }
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

3. Paginate list fields where appropriate

Query depth isn’t the only thing to worry about. We should also be conscious of how query amount could affect the performance of our API.

In the following example, if there were 10 Department, each with 100 Employees, this query would attempt to return 100,000 nodes.

query{
  searchAllDepartments( {
      deptName
      employee{
        employeeName
        city
        country
        deptId
        dob
        email
        employeeId
      }
    }
}
Enter fullscreen mode Exit fullscreen mode

To solve this we can make use of Pagination . With Spring boot its very easy . Just we need to extend PagingAndSortingRepository interface from our Repository and use the implement the methods
in Service class

4. Improve validation and sanitization
Validation and sanitization are standard web application security practices. When you accept data from a user, you should always validate and filter that user-provided data because it could be malicious.

5. Use timeouts
When we request data from downstream services or data sources, there are various reasons why it may take a long time to respond. The services may be down, queries may be expensive, or something else might be going on. Regardless of the reason, we don’t want our GraphQL API to hang for too long, waiting for a response.

To prevent this, we need to use timeouts to keep from slow or unresponsive services impacting performance for subsequent
queries.

We can make use of below property to set timeout from Spring application.properties.

spring.jpa.properties.javax.persistence.query.timeout=60000 #The value is the timeout period in milliseconds

6. Mask errors

When server or downstream service errors occur, it’s a good idea to mask/hide the exact specifics of what went wrong from the client. Rather we should display custom exception message

Informing the client about error details in the server exposes the current server vulnerabilities and opens the door for more concentrated attacks.

Is GraphQL application stable as Rest?

Apps using GraphQL are fast and stable because they control the data they get, not the server.

Summary:

Image description

Conclusion:

GraphQL is an excellent alternative for REST, but not in all situations. Thus, evaluate your application and features that you want to incorporate in it before using the GraphQL. When GraphQL is used in the right scenario, the results can be great!

Discussion (12)

Collapse
jwhenry3 profile image
Justin Henry

I would preferably work in REST environments since it's a bit more explicit and simpler to build out. GraphQL works best for very large and extensive APIs that require that level of flexibility. The size and purpose of an app should determine which to use more than just blanketing all of the web with one or the other.
EX: Simple NextJS apps that have a few endpoints benefit more from very small, concise REST API endpoints, whereas a gradually growing system that frequently adds new features would benefit from GraphQL more.

Collapse
arpanforgeek profile image
Arpan Bandyopadhyay Author

I agree. Thanks for your valuable comment .

Collapse
scottshipp profile image
scottshipp

In many applications it would be no better to use graphql than an ordinary json response. The use cases for a single endpoint serving various needs through a queryable format are far fewer in practice.

Collapse
arpanforgeek profile image
Arpan Bandyopadhyay Author

I agree with you sir 😊 But now a days GraphQL is becoming famous and being used in many companies like Facebook, Netflix , Instagram etc etc. Though graphQL community is smaller than Rest but its growing very fast .

Collapse
iamsarthakk profile image
Sarthak kumar

Great Article, Can you please elaborate why we shouldn't change the application to use graphql if it already has REST? I think it would still be worth it if our requirements are continuously changing and when it can give us a huge performance boost. Still learning about GraphQL so not much confident if I should migrate the REST application to graphql.

Collapse
arpanforgeek profile image
Arpan Bandyopadhyay Author

Thanks for reviewing my post . If you are already using Rest and you have simple application , you are not playing with so much data , you are not fetching data from multiple resource at a time, and if your api/services are resource based then you should not move to GraphQL.. Because Rest can handle all of these very easily and Rest has very good dev community support . GraphQL is still growing and switching to a new technology is always costly . If your application is data centric and you need to handle billions of data from multiple resource and your application is not resource based then you can request your business to move to GraphQL. Otherwise Rest is good .

Collapse
thenickest profile image
TheNickest

Thanks!

Collapse
codepunter profile image
codepunter

how to host it using apache?

Collapse
arpanforgeek profile image
Arpan Bandyopadhyay Author • Edited on

Spring boot has embedded tomcat . You just need to use some command based on the build tool you are using (gradle/maven)

Here is the documentation :
appsdeveloperblog.com/run-spring-b...

But if you wish to deploy it to external tomcat then first you have to exclude embedded tomcat from build.gradle/pom.xml then deploy it. (But this is not recommended)

Here is the documentation :

codezup.com/deploy-spring-boot-war...

Collapse
ireznik profile image
Ilja Reznik

One thing I miss in this post: exposing an api for the public usage has one great advantage. Versioning of the api becomes obsolete with graphql

Collapse
emwadde profile image
emwadde
Collapse
arpanforgeek profile image
Arpan Bandyopadhyay Author • Edited on

Yep Sir !!. Taken reference from not only this . other documents also. Here are the links . These also very useful :

  1. blog.logrocket.com/why-you-shouldnt-use-graphql/

  2. howtographql.com/basics/1-graphql-...

  3. blog.api.rakuten.net/graphql-vs-rest/

and there are many.

But almost everyone used apollo graphql where I have used Spring boot and Java and from security part also I used Spring security reference .

Here I was trying to document where and when we should use GraphQL by reading many other resouces and consolidating their useful content so that any one who is reading my blog will have clear idea without referirng so many other documents .