opencodez

GraphQL Tutorial #1 – Introduction to GraphQL

Introduction :

GraphQL is a query language for your API and it is also a set of server-side runtimes to execute these queries. It is a powerful alternative to the REST. The best part is that you can implement it in any language. GraphQL is used for reading, writing and subscribing to get a real-time update of any data changes. Each of these operations requires only one string called GraphQL query. In REST, we need different endpoints for fetching predefined structure of data. But in GraphQL, we need only one single endpoint for fetching any data we want.

GraphQL was developed by Facebook and it is open-sourced. Facebook has used it for a couple of years internally before open-sourcing it in 2015. GraphQL returns what you ask for. For example, if you have a database of users with xnamex and xaddressx stored, you can get only the xnamex of all users or xaddressx of all users. It helps the application by not fetching any extra data and in turn, improves the performance on low network and low memory devices. Developing the same architecture on REST will result in more complex architecture. This is the main reason Facebook has started using it with native mobile apps in 2012, as an alternative to the REST APIs. Although the initial intention was to use it primarily with native mobile apps, GraphQL is gaining popularity on the web developers community mostly these days.

After it was open-sourced, many big companies have started to adopt GraphQL. Companies like Github, The New York Times, Pinterest, Shopify, Circle, Twitter etc. uses GraphQL in their production. Here is a list of case studies of different companies using GraphQL in production.

Why GraphQL :

If you are familiar with REST APIs, you know that we need different endpoints for fetching different data. You can make HTTP request on different endpoints to get different structured data. GraphQL allows you to get the data that is actually required by your application. It simplifies the data fetching and arrangement process. You will get what you want and in the format that you have requested. The return value of a GraphQL query is a JSON object.

Let me quickly show you a couple of examples to make it more clear.

1. Example 1 :

Suppose, we have one database storing information of book authors with the attributes id, firstName, lastName, and age. We have one object type xAuthorx to store this information.

In REST, for fetching the list of all authors, we need to create one endpoint like YOUR_URI/api/authors. The application will have to make one GET request on this endpoint to fetch the list of all authors. This will return one list of xAuthorx objects containing all fields (id, firstName, lastName and age) in each object.

So, even if our application is not using all these four fields, we are receiving them from the server.

Now, if we are using GraphQL to implement the same server, we can define what we need using a simple query parameter. For example, if our application requires only the first name of the Authors, we can make one request with the following query :

{
  authors {
    firstName
  }
}

This will return us the list of all authors with only the xnamex property like below :

{
  "data": [
    {
      "firstName": "Alex"
    },
    {
      "firstName": "Bob"
    }
  ]
}

The return value is a JSON object.

Similarly, the GraphQL query for fetching the xfirstNamex and xlastNamex properties will look like :

{
  authors {
    firstName

    lastName
  }
}

The output of this query will look like as below :

{
  "data": [
    {
      "firstName": "Alex",

      "lastName": "Brown"
    },
    {
      "firstName": "Bob",

      "lastName": "Walker"
    }
  ]
}

If you want to change the order of the parameters in the response JSON object, just change them in the GraphQL query. For example, the following query will alter the positions of the xfirstNamex and xlastNamex parameters :

{
  authors {
    lastName
    firstName
  }
}

With GraphQL, we can explicitly request just the part that is actually required by the application. It makes the payload of the transformation smaller and improves the processing of both client and server.

All these queries are used only for a single endpoint in GraphQL.

Example 2:

We already have one xAuthorx object containing id, firstName, lastName and age. Letxs add a bit more complexity by adding one more object xBookx to this example. This object will hold the id(id), book name (bookName) and the id of the author of this book (authorId).

Suppose our problem is to find out the name of the books published by all authors and the detail of each author.

For a typical REST design, we will have to create two endpoints like xYOUR_URI/api/authorsx and xYOUR_URI/api/books/?authoridx. The first API will return us the list of all authors and the second API will return us the list of all books for an author with id xauthoridx. That means we will have to make one network request to get the list of all authors and one request each for all the authors. If we have 10 authors in our database, 11 network calls will require to fetch all information.

Now, if we are using GaphQL, it will be a simple one GraphQL query to fetch all the information I have mentioned above. The query will be like below :

{
  authors {
    firstName
    lastName
    book {
      name
    }
  }
}

The output will be :

{
  "data": [
    {
      "firstName": "Alex",
      "lastName": "Brown",
      "book": [
        {
          "name": "This is the universe"
        },
        {
          "name": "Your World"
        }
      ]
    },
    {
      "firstName": "Bob",
      "lastName": "Walker",
      "book": [
        {
          "name": "Book X"
        }
      ]
    }
  ]
}

As you can see that with one single GraphQL query, we can fetch all these complex data set. If you want, you can add any other parameters of xAuthorx or xBookx to this query. GraphQL will handle it internally. Without loading the data from multiple URLs in a REST environment, we can fetch complex data in a single request using GraphQL. Even on slow internet connection, applications using GraphQL will be much faster.

GraphQL is a strongly typed query language. It is written in GraphQL SDL or Schema definition language. Various data types are defined that can be used in a GraphQL object and query. For example, the type of the above xAuthorx and xBookx objects will look like below :

type Author {
  id: ID!
  firstName: String
  lastName: String
  age: Float
  book: Book
}

type Book {
  id: ID!
  name: String
  authorid: ID!
}

Using types and fields, GraphQL APIs are organized. The App knows what it is asking for and if the type is mismatched, GraphQL provides meaningful errors.

GraphQL and REST :

REST is one of the most popular choices for developing client-server architecture. GraphQL is a trending alternative for REST APIs. As mentioned before, it is already adopted by a lot of well-known companies and the list is growing.

Rest provides Create, Read, Update and Delete operations or simply CRUD operations to manipulate data

1. GraphQL provides only a single endpoint for all queries. REST requires separate endpoints for separate queries. Using a single endpoint we can have different types of data we want. For REST, we need to call different endpoints for different data set.

2. The queries of the GraphQL are customizable. We can request for data what we actually want. It prevents the application from unnecessary data fetching. But in REST, we canxt control the return data types for a specific API. An API will return the data based on its design. GraphQL makes the payload size smaller and it helps the data loading faster even on a low network condition.

3. We can receive complex data set in GraphQL easily. REST requires multiple network requests for that. The second example above explains it well. It makes the application faster. If multiple REST API calls are required, the application will be slower to operate.

4. GraphQL provides easy debugging with its data types. The data type can be verified during compile time. REST doesnxt have any such features.

5. You can add new fields to your GraphQL API without breaking the existing queries. You can deprecate the unused fields. But in REST, you need to create a new version of API for that.

6. GraphQL doesnxt provide any inbuilt caching support. REST APIs can leverage HTTP caching. But using third-party libraries, you can have the caching mechanism on GraphQL as well.

Conclusion :

Many peoples still preferred to use REST over GraphQL. It depends on the requirement but if you have a complex data representation and if your design requires multiple queries in REST to fetch the required data, GraphQL is a perfect fit in this case. GraphQL also makes the development process faster as compared to REST.

Tutorial Index:

  1. GraphQL Tutorial #1 -Introduction
  2. GgraphQL Tutorial #2 x Setting Basic Project in GraphQL
  3. GraphQL Tutorial #3 x GraphQL Components
  4. GraphQL Tutorial #4 x GraphQL Operations
  5. GraphQL Tutorial #5 x Introduction to Apollo GraphQL
  6. GraphQL Tutorial #6 x 51 Most Important GraphQL Interview QxA

x