Is GraphQL better option than Rest ?
Tags: beginners, graphql, webdev, java
Published: 2021-12-27 12:33:59

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****
    }
  }
}
```

and I will get Response like below : 

```
{
  "data": {
    "searchDeptByName": {
      "employee": [
        {
          "employeeName": "Arya"
        },
        {
          "employeeName": "Tushar"
        },
        {
          "employeeName": "Rekha"
        },
        {
          "employeeName": "Roshan"
        }
      ]
    }
  }
}
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6y3xo81e5lg16n3hghut.png)
 

**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
      }
    }
  }
}
```
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
            }
          }
        }
      }
    }
  }
}
```

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"
      }
    }
  ]
}
```
**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
      }
    }
}
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kfvf8rd56yzuizauz61p.PNG)
 


**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!