cancel
Showing results for 
Search instead for 
Did you mean: 

Why GraphQL Is Interesting for Magento 2

akent99
Regular Contributor

GraphQL is an API style that Facebook has released as open source that is getting traction on other projects, including GitHub. This blog post explores reasons why GraphQL could be interesting for Magento 2 to add alongside REST and SOAP as web API protocols.

 

API “Graphs”

 

The name GraphQL came from Facebook where it is used as the API to query the Facebook social graph. GraphQL is part way between query languages such as SQL with JOIN and aggregation functions, and REST or SOAP, where the server decides on the structure of data it makes available. For example, a GraphQL request always specifies what data to be returned (similar to the SELECT line of an SQL query), but GraphQL provides no query operators such as GROUP BY or SUM. While there is no JOIN operator, it is normal for a server to make fields available to navigate to other related data structures. Thus, GraphQL allows a client to navigate through a type graph defined by a server. More on this later.

 

Types

 

GraphQL is strongly typed – you define the exact structure of what can be returned. For example,

 

 

type Product {
    id: Int
    sku: String
    title: String
    description: String
    . . .
}

 

In the case of Magento, types would be generated automatically from the set of available attributes for entities such as “Product”, or from the return type of service contracts.

 

Interoperability

 

The simplicity of the GraphQL type system makes it easier to integrate with a wider range of programming languages. It also aligns well with existing Magento 2 service contracts. This makes it straightforward to add GraphQL support to Magento 2 alongside REST and SOAP.

 

There are several client-side JavaScript libraries available for integrating GraphQL with JavaScript rendering frameworks. For example, Facebook backs Relay for use with React. There is also Apollo. These libraries have various features such as automatic client side caching of data.

 

Data Retrieval

 

GraphQL supports concepts of both read request (queries to read data) and write requests (mutations allow inserting/updating/deleting database contents).

 

When you specify a query to retrieve data, you must also specify what fields you want to return. This aligns well with the new proposed Magento query API (a new persistence layer for Magento to separate database access from business logic), where we want to minimize data to retrieve and transfer.

 

 

{
    product(sku: “MJ01”) {
        sku
        title
    }
}

 

 

Data is returned in JSON format.

 

 

{
    “data”: {
        “product”: {
            “sku”: “MJ01”,
            “title”: “Mens Jacket in leather”
        }
    }
}

 

 

Note that fields map on to function calls. For example, the “sku” field above may be a call to a simple getter function of a product record fetched from the database. But, fields can also invoke any defined code, such as a “relatedProducts” field returning an array of product information about related products. This allows a query to fetch data from multiple nodes in a graph of information in a single query. It is this sort of graph navigation that makes GraphQL more powerful than REST.

 

 

{
    product(sku: “MJ01”) {
        title
        relatedProducts {
            sku
            title
        }
    }
}

 

 

Asking for specific data fields may feel burdensome initially, but there are multiple benefits:

 

  • It reduces network transfer, which can be important for mobile devices.
  • It allows for performance improvements, as the server knows exactly what fields are wanted, enabling query optimizations to be made. (In the case of Magento 2, SQL joins can be avoided for EAV attributes that the client does not need returned.)
  • It allows for schema evolution. New fields (including new linkages between types) can be added without breaking existing applications. Old fields can be removed when no old clients request that field. (GraphQL also supports the concept of marking fields as deprecated for documentation purposes.)

 

Request Batching for Performance

 

GraphQL makes multiple resources or services available from a single endpoint (URL), unlike REST, which uses a separate URL per resource. One request can include multiple queries, if desired, with an aliasing scheme to avoid name collisions. This is useful to share the per HTTP request overhead with several requests.

 

 

{
    p1: product(sku: “MJ01”) {
        sku
        title
    }
    p2: product(sku: “MJ02”) {
        description
    }
}

 

 

In the case of Magento, this would avoid the HTTP and PHP startup overhead per REST call that is currently incurred.

 

Introspection

 

Having a well-defined type system has another benefit. GraphQL endpoints publish their schema allowing interactive clients such as GraphiQL (pronounced “graphical”) to query what a site supports. This includes documentation of all data structures and methods that are available. GraphIQL is available as a Chrome extension, making it straightforward to install and use. With Magento, the GraphQL schema would most likely be dynamically generated from the available service contracts published by loaded modules and entity attribute definitions, allowing developers to determine exactly what a specific Magento site supports.

 

Other Considerations

 

GraphQL has some issues that need further exploration.

 

  • With the performance improvements of HTTP/2, the benefits of merging HTTP requests may be less pronounced.
  • GraphQL supports both GET and POST requests, however merging multiple requests or using POST for sending queries can make caching harder with technologies such as Varnish.
  • Web Application Firewall (WAF) rules can be harder to protect against attacks as it may be necessary to parse the contents of a POST request rather than blocking particular REST URLs.

 

These issues are not necessarily blockers, but need further investigation.

 

Conclusion

 

To wrap up this post, it is not yet definite that Magento 2 will adopt GraphQL. However, there are a number of benefits that make it worthwhile considering, especially considering it can be glued on top of existing service contracts. GraphQL is being reviewed at present to see if it would help the Progressive Web App (PWA) initiative currently underway (which includes using JavaScript frameworks such as React, Angular, Vue, or Polymer to build Magento store fronts). If you have used GraphQL or have an opinion on whether you think GraphQL is a good fit for Magento, please leave a comment!

 

 

11 Comments