What is GraphQL and How to Use it

What is GraphQL? How to Use It with Shopify

In this tutorial, you will learn about GraphQL and how to use it. This would be useful to you if you have a basic knowledge of HTTP REST APIs. So, GraphQL is normally described as ‘a better REST’. So basically, you make request to some endpoints and get some data. GraphQL does it better. Let’s see why.

  1. What is GraphQL
  2. How GraphQL Works
  3. A Short GraphQL Demo

 

1. What is GraphQL?

According to Graph website, www.graphql.org, ‘GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data’. Let’s break this down! Let’s take REST API for example. If you want some data, you make a HTTP request to some endpoint, say, http://myserver/orders, these are the steps:

  • send the api request to the endpoint
  • the endpoint executes a function that connect to the database and fetches the data
  • the data is sent back to you as a json response

For example, the below figure shows the response from a Shopify orders API.

Problem of overfetching with REST APIs
Problem of overfetching with REST APIs

 

Do yo know that what is returned is just  a single order data! This is the problem of overfetching with REST APIs. You see that mode of the information returned are not needed. GraphQL solves this problem by allowing you to fetch only the  data you need, nothing more, nothing less.

We also have the problem of underfetching. In this case, REST API response returns field including id field. These id fields relates to other entities. For instance, productId may be returned where you actually need the description and price. GraphQL also solves this problem of underfetching.

 

4. How GraphQL Works

As mentioned previously, GraphQL is a query language and runtime. So the queries has to be defined first. Then the runtime has to be setup on a server. Normally, you will find some library or service to achieve this. Here are the steps of getting data from GraphQL

  • send a query to the GraphQL service
  • the service validates and executes the query
  • the query is executed and the data is fetched
  • the result is sent back to the client as a linked list(or graph)

Let me now show you an equivalent of the GraphQL equivalent of the orders API which returns only the data we need.

Query

query{
  orders(first:1){
    edges{
      node{
        id
        name
      }
    }
  }
}

 

Response

{
  "data": {
    "orders": {
      "edges": [
        {
          "node": {
            "id": "gid://shopify/Order/3217147494577",
            "name": "#1001"
          }
        }
      ]
    }
  }

 

3. GraphQL Demo

Let’s now take an example of working with GraphQL. At this point, I would recommend you also watch the video the see how it works. This demo would be based on a Shopify app that return a list of products and displays them on the console. The products would be displayed with the click of a button.

Prerequisite: You need to have a basic Shopify App. I’ll update the step by step on this.

Follow the steps below:

Step 1 – Create functional component. I call it GetProducts.js

Step 2 – Import the ggl library as well as the usQuery library like so:

import gql from 'graphql-tag';

import {useQuery } from 'react-apollo';

 

Step 3 – Add a button to the component and a clickHandler. This function is shown below:

function GetProducts() {
    return (
        <div>
            <button onClick={showProduts}>Show Products</button>
        </div>
    )
}

 

Step 4 – Define the following variables in the component

const GET_PRODUCTS = gql`
{
products(first: 3) {
    edges{
    node{
        id
        title
    }
    }
}
}
`;

let data = useQuery(GET_PRODUCTS)

The first variable GET_PRODUCTS is the GraphQL query while the second variable data would hold the response data returned.

 

Step 5 – Now write the function to simply log the data to the console like so:

function showProducts(){
   console.log(data)
}

 

Step 6 – Finally, include the GetProducts component in the index.js component. Then run shopify server. Go to the App page and click on the button. Open the console and see that a list of products is returned. This is shown below:

Response from GraphQL Query
Response from GraphQL Query

I recommend you watch the video as it makes it very clear.

I would be making a more comprehensive beginner tutorial on GraphQL in the coming days.

Admin bar avatar

kindsonthegenius

Kindson Munonye is currently completing his doctoral program in Software Engineering in Budapest University of Technology and Economics

View all posts by kindsonthegenius →

Leave a Reply

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