#01 – Introduction – Learn GraphQL

In this post, we have discussed what is GraphQL, the differences between REST API’s and GraphQL API development architectures, and an example scenario to elaborate on the differences between the two approaches.

What is GraphQL?

  • It is a new API development standard
  • It is a query language for API’s
  • It provides declarative syntax to fetch data from multiple data sources
  • It’s an alternate to REST API development architecture
  • Unlike REST, it exposes only a single endpoint to respond to queries
  • It solves the problem of over-fetching and under-fetching the data
  • It speeds up the development because we don’t need to adjust API every time the front-end app data requirements are adjusted

What are the differences between REST and GraphQL architectures?

  • A REST endpoint provides all the data (fields) returned by the endpoint whereas the GraphQL endpoint only provides the requested data (fields) thus improving the performance
  • In the case of REST, multiple requests are made to fetch data from different REST endpoints whereas the GraphQL endpoint can combine and return data from multiple queries in a single request

Example Scenario:

Let’s say you have a front-end application page where you want to display the author’s name with 3 posts of that author and 3 comments on each post. If we have a REST API we will call 3 endpoints to implement this feature:

  1. Call /users/<id> endpoint to fetch the user (author) information
  2. Call /users/<id>/posts endpoint to fetch all posts by the user (author)
  3. Call /posts/<id>/comments endpoint to fetch all comments on each post

As you can see that we need to call 3 endpoints separately to get all the required data. Moreover, we are fetching all user posts and all post comments whereas we only need to display 3 posts and 3 comments on each post.

GraphQL simplifies this process and provides a more efficient way to handle these kind of scenarios. The above data can be received from single query to GraphQL API as follows:

{
   user(id: "123"){
      name,
      posts(id: "12344...", last: 3){
         title,
         description,
         comments(id: "453355...", last: 3){
            text,
            author
         }
      }
   }
}

In the next post, we will learn about the core concepts of the GraphQL.

Leave a Comment

Your email address will not be published. Required fields are marked *