• GraphQL logo. Source: GraphQL 2019a.
    GraphQL logo. Source: GraphQL 2019a.
  • Several REST endpoint requests can be replaced with a single GraphQL query. Source: Poirier-Ginter 2019.
    Several REST endpoint requests can be replaced with a single GraphQL query. Source: Poirier-Ginter 2019.
  • A comparison of GraphQL and REST. Source: AltexSoft 2019.
    A comparison of GraphQL and REST. Source: AltexSoft 2019.
  • GraphQL query extracts a tree from the app data graph. Source: Pandya 2016.
    GraphQL query extracts a tree from the app data graph. Source: Pandya 2016.
  • GraphQL query, response and schema. Source: Kurtula 2018.
    GraphQL query, response and schema. Source: Kurtula 2018.
  • Execution phases of a GraphQL query. Source: Devopedia 2019.
    Execution phases of a GraphQL query. Source: Devopedia 2019.

GraphQL

Avatar of user gurumoorthyP
gurumoorthyP
1232 DevCoins
Avatar of user vivex
vivex
94 DevCoins
Avatar of user arvindpdmn
arvindpdmn
20 DevCoins
4 authors have contributed to this article
Last updated by him2312
on 2019-05-27 06:19:16
Created by vivex
on 2019-02-02 17:47:46

Summary

GraphQL logo. Source: GraphQL 2019a.
GraphQL logo. Source: GraphQL 2019a.

Often when client apps wish to get data, they have to work with available REST APIs and live with their limitations. To obtain data, they make multiple API calls. In the process, they end up overfetching data and using only some of it. On slow connections, this dampens user experience.

GraphQL is an alternative to traditional REST APIs but its not meant to replace REST. You can describe your data with a well-defined GraphQL schema. Clients have the flexibility to get as much data as needed. While API calls are similar to querying databases, GraphQL is not a database language. GraphQL also interfaces nicely with frontend JavaScript frameworks such as React.

GraphQL was created at Facebook and then open sourced. It's now managed by GraphQL Foundation.

Milestones

2012

Facebook's iOS and Android apps become native apps. These need an API to retrieve Facebook's News Feed. RESTful APIs and Facebook Query Language (FQL) are available but developers see a gap between what apps wanted and the queries that servers exposed. Developers had to write lot of code on server side to prepare data and on client side to consume it. It's to solve this problem that Nick Schrock of Facebook creates a first prototype called SuperGraph. This is renamed to GraphQL.

2015

Facebook open sources GraphQL, which is also released as a draft specification. This move is partly influenced by Facebook's React that was open sourced in 2013, Facebook's React Native that's also open sourced in 2015 and Facebook's Relay that provides a framework for building mobile apps based on React, React Native and GraphQL.

Jun
2018

GraphQL specifications exits "Draft RFC" status. It defines Type System Definition Language and delivery of live data over GraphQL subscriptions.

Nov
2018

GraphQL Foundation is formed, to be hosted by the Linux Foundation. This paves the way for a vendor-neutral development of GraphQL. By now, GraphQL is being used by Airbnb, Audi, GitHub, Netflix, Shopify, Twitter, NY Times and many more. At Facebook alone, it powers billions of API calls every day. In March 2019, GraphQL Foundation announces collaboration with the Joint Development Foundation.

Discussion

  • What exactly is GraphQL?
    Several REST endpoint requests can be replaced with a single GraphQL query. Source: Poirier-Ginter 2019.
    Several REST endpoint requests can be replaced with a single GraphQL query. Source: Poirier-Ginter 2019.

    GraphQL is described as "a query language for APIs and a runtime for fulfilling those queries with your existing data". You describe your data using a schema. Clients then ask for exactly what they want and nothing more. Thus, control is with the client rather than the server. With SOAP or REST, clients had to work with well-defined endpoints, often making multiple calls to obtain a complete set of data. With GraphQL, a single API call is sufficient to do the same.

    GraphQL is not a database language. GraphQL is also not an implementation. It's an open source specification that can be implemented in any language. A GraphQL service sits between your app and the data. It provides a layer of abstraction. Based on a schema, it does validation on the queries and responses. It's APIs are based on types and fields, not endpoints. Clients no longer need to parse responses, since they get data in a form they want it.

  • Why do we need GraphQL when there's already REST API?
    A comparison of GraphQL and REST. Source: AltexSoft 2019.
    A comparison of GraphQL and REST. Source: AltexSoft 2019.

    It's typical in REST to think of data as a resource. Each resource is exposed via an API endpoint. For example, data about a library would consists of books, authors, branch locations, members, staff, and so on. Each of these is typically exposed via its own endpoint. With GraphQL, the entire data is considered as a single interconnected graph of data points. What does this mean?

    Suppose you wish to know about books written by an author and the branches where these are available. With REST, we would need to make multiple queries since the information might come from multiple endpoints. With GraphQL, a single request is sufficient since relationships among books, authors and branches are all part of the same data graph.

    A book could be identified by a unique integer. GraphQL can validate this. Errors due to type mismatches are caught early by the GraphQL service instead of allowing applications to fail in unpredictable ways. GraphQL also has a feature called Subscriptions that makes it easier to update applications with real-time data.

  • Why does GraphQL treat my data as a graph?
    GraphQL query extracts a tree from the app data graph. Source: Pandya 2016.
    GraphQL query extracts a tree from the app data graph. Source: Pandya 2016.

    GraphQL provides a layer of abstraction between the application and the data storage. In this abstraction, GraphQL models data as nodes. Connections among these nodes are edges. Thus, data is a graph of interconnected objects rather than resources accessed via multiple endpoints. We can call this the application data graph.

    Consider a library's catalogue of books. Books and authors are the nodes and they are interconnected. An author may have written multiple books. A book may have co-authors. If we query for a specific book and all its authors, GraphQL is basically extracting a subtree from the data graph. Let's note that a tree is also a graph but without any loops.

    A tree has a hierarchical structure. The beauty of GraphQL is that the query to obtain a subtree from the graph also has a similar tree structure. We can say that the query and its response have same data shape. This makes it easier to write queries and process the responses.

  • What are the advantages of using GraphQL?
    GraphQL query, response and schema. Source: Kurtula 2018.
    GraphQL query, response and schema. Source: Kurtula 2018.

    GraphQL is a specification. Implementations of the GraphQL server in various languages are available. Client implementations are also available to ease the developer's job.

    GraphQL does not impose how or where data should be stored. Data may come from multiple databases or REST APIs. There's no need to discard your existing REST API endpoints. GraphQL can work with them. In any case, GraphQL presents a single source of truth. GraphQL eliminates the need to build separate API endpoints for each type of client (web vs mobile).

    GraphQL eliminates the "chattiness" or the N+1 problem that's inherent in REST APIs. Another point of efficiency is that data is not overfetched.

    A UI component can obtain all the data is needs without worrying about how this maps to databases or multiple endpoints. Data fetching is declarative and UI-driven, which is also why many frontend frameworks (React, Angular, Vue) interface nicely with GraphQL.

    GraphQL is strongly typed. With introspection, we can retrieve GraphQL schema. Versioning like done in REST APIs is not needed. GraphQL API can be updated at field level.

  • What are the phases of a query in GraphQL?
    Execution phases of a GraphQL query. Source: Devopedia 2019.
    Execution phases of a GraphQL query. Source: Devopedia 2019.

    A GraphQL has to be understood by a GraphQL service before it can respond with the correct data. A GraphQL service tokenizes the query string and then parses the tokens to build the Abstract Syntax Tree (AST). It then validates the query against the schema. If invalid, an error response is returned. If valid, the AST may be reduced to a form that's simpler to execute. If there are any defined query analyzers, they will be called. During execution, resolvers are called to obtain the actual data pertaining to each field.

    The GraphQL client is not part of the GraphQL specifications but clients simplify processing. Different clients handle the queries and responses differently. For example, Apollo Client normalizes the response and caches it. It also minimizes the original query for efficiency.

  • Could you briefly introduce common GraphQL terms?

    Apollo Docs has published a handy GraphQL glossary. Another source is GraphQL's learning page. Here we describe some essential terms:

    • Query: A read-only operation to get data from a GraphQL service.
    • Mutation: While a query could be designed to do data writes, this is not recommended. An explicit mutation is recommended.
    • Field: The basic unit of data that we can obtain. GraphQL is in fact about selecting fields on objects.
    • Fragment: A set of fields that can be reused across multiple queries.
    • Argument: Every field and nested object can have an argument, thus enabling us to filter or customize the results.
    • Alias: To avoid naming conflicts in the results, aliases are useful. For instance, we can query the same object with different arguments and get the results in different aliases.
    • Directive: This can be attached to a field or fragment to dynamically affect the shape of data. Mandatory directives are @include and @skip to either include or skip a field based on a condition.
  • What are some criticisms of GraphQL?

    It's been said that REST can do what GraphQL does. Query parameters can filter data. JSON Schema can be used for type validation. OData can be used as a query language. These alternatives are better for small applications where GraphQL can be an overkill. GraphQL comes with the need to write resolvers.

    Error handling is more complex since the response has to be parsed. An error will be returned as a HTTP 200 OK status. This also means that we can't use monitoring tools that mostly ping an endpoint without a request body and look at only status codes.

    REST calls conform to HTTP semantics and web caching is easier due to multiple endpoints. With GraphQL, given a single endpoint, web caching is harder to implement. Tools such as Relay or Dataloader can help.

    Performance can be an issue since clients can construct complex queries. This is more so for data coming from third parties. With REST, an endpoint can be designed and fine tuned for a specific query.

Sample Code

  • # Source: https://fullstackmark.com/post/17/building-a-graphql-api-with-aspnet-core-2-and-entity-framework-core
    # Accessed 2019-05-22
     
    # Schema
    type Student {
      id: ID
      firstName: String
      lastName: String
      birthDate: Date
      email: String
      courses: [Course]
    }
     
    type Course {
      id: ID
      title: String
      description: String
      startDate: Date
      endDate: Date
    }
     
    # A query type where inclusion of ID is mandatory
    type Query {
      student(id: ID!): Student
      course(id: ID!): Course
    }
     
    # An example query
    {
      student(id: "10") {
        firstName,
        lastName,
    	email,
        courses {
          title
        }
      }
    }
     
    # Response to the above
    {
      "firstName": "Mark",
      "lastName": "Macneil",
      "email": "This email address is being protected from spambots. You need JavaScript enabled to view it.",
      "courses": [
        {"title": "Advanced ASPNET Core" },
        {"title": "Introduction to GraphQL" }
      ]
    }

References

  1. AltexSoft. 2019. "GraphQL: Core Features, Architecture, Pros and Cons." Altexsoft, March 23. Accessed 2019-05-21.
  2. Apollo Docs. 2019. "GraphQL Glossary." Apollo. Accessed 2019-05-21.
  3. Ashwini, Amit. 2017. "What Is The Difference Between React.js and React Native?" Cognitive Clouds, September 9. Accessed 2019-05-22.
  4. Baer, Eric. 2018a. "A GraphQL Primer: Why We Need A New Kind Of API (Part 1)." Smashing Magazine, January 24. Accessed 2019-05-21.
  5. Baer, Eric. 2018b. "A GraphQL Primer: The Evolution Of API Design (Part 2)." Smashing Magazine, January 31. Accessed 2019-05-21.
  6. Bustamam, Rasheed. 2018. "GraphQL: front-end queries made easy." freeCodeCamp, June 12. Accessed 2019-05-21.
  7. Byron, Lee. 2015. "GraphQL: A data query language." Facebook Code, September 14. Accessed 2019-05-21.
  8. Byron, Lee. 2018. "GraphQL Spec: tag June 2018." GraphQL, on GitHub, June 11. Accessed 2019-05-21.
  9. Dedmon-Wood, Morgan. 2018. "Getting Started with Apollo Client and GraphQL." SlideShare, March 01. Accessed 2019-05-21.
  10. Gilling, Derric. 2018. "REST vs GraphQL APIs, the Good, the Bad, the Ugly." Moesif Blog, February 27. Accessed 2019-05-21.
  11. GitHub Developer. 2019. "Introduction to GraphQL." GraphQL API v4, GitHub. Accessed 2019-05-21.
  12. GraphQL. 2019a. "Homepage." GraphQL. Accessed 2019-05-21.
  13. GraphQL. 2019b. "Queries and Mutations." GraphQL. Accessed 2019-05-21.
  14. GraphQL Ruby. 2018. "Phases of Execution." June 01. Accessed 2019-05-21.
  15. Herrera, Esteban. 2018. "5 reasons you shouldn't be using GraphQL." Blog, LogRocket, via Medium, September 20. Accessed 2019-05-21.
  16. Kurtula, Aurel. 2018. "Exploring GraphQL API." Dev.to, March 25. Accessed 2019-05-23.
  17. Lardinois, Frederic. 2018. "Facebook’s GraphQL gets its own open-source foundation." TechCrunch, November 06. Accessed 2019-05-21.
  18. Lombard, Jeff. 2018. "When and why to use GraphQL." Medium, November 13. Accessed 2019-05-21.
  19. Martiny, Amaury. 2018. "GraphQL vs. REST - A GraphQL Tutorial." Toptal. Accessed 2019-05-21.
  20. Mohilo, Dominik. 2018. "GraphQL is good, but it is not an alternative to 'real' REST services." Interview with Christian Schwendtner, JAXenter, March 29. Accessed 2019-05-21.
  21. Pandya, Dhaivat. 2016. "GraphQL Concepts Visualized." Apollo Blog, via Medium, August 18. Accessed 2019-05-21.
  22. Poirier-Ginter, Michael. 2019. "Using Node.js Express to Quickly Build a GraphQL Server." Blog, Snipcart, March 28. Accessed 2019-05-22.
  23. Scott, James. 2018. "Interview With GraphQL Co-Creator Lee Byron." Blog, Nordic APIs, September 25. Accessed 2019-05-21.
  24. Stuart, Mark. 2018. "GraphQL Resolvers: Best Practices." PayPal Engineering, via Medium, December 11. Accessed 2019-05-21.
  25. Talla, Anil. 2018. "GraphQL & SDL." Medium, August 27. Accessed 2019-05-21.
  26. The Linux Foundation. 2019. "The GraphQL Foundation Announces Collaboration with the Joint Development Foundation to Drive Open Source and Open Standards." Press release, The Linux Foundation, March 12. Accessed 2019-05-21.
  27. Wieruch, Robin. 2018. "Why GraphQL: Advantages, Disadvantages & Alternatives." July 03. Accessed 2019-05-21.

Milestones

2012

Facebook's iOS and Android apps become native apps. These need an API to retrieve Facebook's News Feed. RESTful APIs and Facebook Query Language (FQL) are available but developers see a gap between what apps wanted and the queries that servers exposed. Developers had to write lot of code on server side to prepare data and on client side to consume it. It's to solve this problem that Nick Schrock of Facebook creates a first prototype called SuperGraph. This is renamed to GraphQL.

2015

Facebook open sources GraphQL, which is also released as a draft specification. This move is partly influenced by Facebook's React that was open sourced in 2013, Facebook's React Native that's also open sourced in 2015 and Facebook's Relay that provides a framework for building mobile apps based on React, React Native and GraphQL.

Jun
2018

GraphQL specifications exits "Draft RFC" status. It defines Type System Definition Language and delivery of live data over GraphQL subscriptions.

Nov
2018

GraphQL Foundation is formed, to be hosted by the Linux Foundation. This paves the way for a vendor-neutral development of GraphQL. By now, GraphQL is being used by Airbnb, Audi, GitHub, Netflix, Shopify, Twitter, NY Times and many more. At Facebook alone, it powers billions of API calls every day. In March 2019, GraphQL Foundation announces collaboration with the Joint Development Foundation.

Tags

See Also

  • REST API to GraphQL Migration
  • GraphQL Design Patterns
  • Representational State Transfer
  • Type Introspection

Further Reading

  1. Introduction to GraphQL
  2. Baer, Eric. 2018a. "A GraphQL Primer: Why We Need A New Kind Of API (Part 1)." Smashing Magazine, January 24. Accessed 2019-05-21.
  3. Baer, Eric. 2018b. "A GraphQL Primer: The Evolution Of API Design (Part 2)." Smashing Magazine, January 31. Accessed 2019-05-21.
  4. Martiny, Amaury. 2018. "GraphQL vs. REST - A GraphQL Tutorial." Toptal. Accessed 2019-05-21.
  5. Apollo Docs. 2019. "GraphQL Glossary." Apollo. Accessed 2019-05-21.

Article Stats

Author-wise Stats for Article Edits

Author
No. of Edits
No. of Chats
DevCoins
5
1
1232
1
0
94
1
1
20
1
0
13
1600
Words
2
Chats
8
Edits
3
Likes
1446
Hits

Cite As

Devopedia. 2019. "GraphQL." Version 8, May 27. Accessed 2019-11-21. https://devopedia.org/graphql