What is GraphQL?

GraphQL is a query language and runtime that was developed by Facebook in 2012 and was released as an open-source project in 2015.

GraphQL allows the client to define the structure of the data it needs and the server returns that exact structure. This eliminates the problem of over-fetching or under-fetching data that often occurs with REST APIs.

For example the following query:

Example

query {
  contacts(filters: [], first: 1) {
    edges {
      node {
        id
        personalName {
          firstName
          lastName
        }
      }
    }
  }
}

will only return the id, personalName.firstName and personalName.lastName of the first contact in your system instead of the entire contact object:

{
  "data": {
    "contacts": {
      "edges": [
        {
          "node": {
            "id": "UGVyc29uOjI=",
            "personalName": {
              "firstName": "Support",
              "lastName": "Desk"
            }
          }
        }
      ]
    }
  }

Querying vs Mutations

An important difference between GraphQL and REST is that separation of Querying, or reading data, and Mutations or writing data.

If you have used a REST API you may be familiar with simply GET'ing a blob of data and making a change and then posting it back. While this can simplify simple CRUD operations, it starts to break down when more complex actions are being requested. For example emailing an invoice is an operation performed on an invoice not a mutation of the data of the invoice itself.

GraphQL allows us to expose all of the actions that you can take on the entities in you system explicitly, if you want to email an invoice you call the emailInvoice(invoiceId) action, which will send the email, and also return the fields you request from the invoice email record.

Example

mutation {
  finance {
    emailInvoice(invoiceId: "SW52b2ljZTox", contactId: "UGVyc29uOjI=") {
      id
      sentAt
      contact {
        name
      }
    }
  }
}