GraphQL in Front End Development

GraphQL in Front End Development

To render data in front end development, we need to make an API call. There are few challenges faced while making a REST API call:

  • The response data needs aggregation in Front End side. Aggregation is costly operations in Javascript.
  • The response data format is not in same format required in UI.
  • API call response has too many items, not required in UI.
  • Less maintenance required for backend developers as UI developers can modify queries as per requirement.
GraphQL is an API query language, which lets the user to ask as per their need. The GraphQL schema will define the queries and fields. Similar to SQL language, you need to write queries to fetch the data exactly needed in UI.

In REST API call, irrespective of user’s need all data will get fetched. But in GraphQL, only the required data need to be mentioned in SELECT query. Only prerequisite is to learn write queries.

GraphQL hugely enhances the performance of web. A simple GraphQL query:

In this example, we only need to display tagline in UI so we requested only for the required field.

No alt text provided for this image
GraphQL provides?
- Fetch data
- Create/Update/Delete operation


Why GraphQL?

  • Aggregation of data

GraphQL schema defines aggregation methods, with these we could fetch data as per need to show in UI. In REST API call, we need to fetch raw data and do these calculations or aggregation in Javascript.

Common aggregation functions are count, sum, avg, max, min, etc.
No alt text provided for this image
  • Fetch data as per your need to show in UI

GraphQL queries are formed to fetch the exact amount of data to show in UI. In REST API call, the server controls the response to be given to UI but in GraphQL the client request for the required data.

e.g.

No alt text provided for this image

In this case, we only need to show 3 fields in UI. So, through the query we only asked for 3 fields. In REST api call, it might have responded with 10 fields as the response is getting decided in backend.

  • Add features to GraphQL API without impacting existing code

To further enhance the functionalities, backend need to add fields and columns. The best part is, new fields will not impact the existing queries or functionalities.

From Front end perspective, GraphQL is one endpoint. Though, GraphQL server connects to multiple backends such as a SQL database, MongoDB database, REST endpoint and another GraphQL. The core of backend server is schema. The schema defines types and which queries should be executed among which database.

In my next article, I will provide more details about how to frame GraphQL queries…

要查看或添加评论,请登录

社区洞察

其他会员也浏览了