Intro to graphQL

June 21, 2020

What is graphQL?

As we can read on graphql site - GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. It is often compared to REST API's. Keep in mind that both REST and graphQL are two different approaches to developing API's. There is no need to rewrite REST API's to graphq, unless it will be beneficial to your project.

Why graphQL?

  • REST may require multiple dependent network requests to get bigger chunks of data. Using graphQL, we can obtain the same data using single query.
  • You ask what you get. If you don't need some data, you can remove field from query. Using REST endpoint you may get data that serves no purpose in your case.
  • One endpoint to get data
  • Type system.
  • GraphQL services can be written in any language.
  • GraphQL playground

Why not graphQL?

  • Does not support web browser caching. Web browsers cache fetched data according to its URL, but graphQL uses single endpoint.
  • Can execute operations slowly if app's design is poor. That can be also said about REST.

Schema

We start using graphQL with defining its most basic component - Schema. Schema represent object and its fields that will be fetched from graphQL endpoint.

type User {
  id: ID!
  name: String!
  email: String!
  age: Int
}

By default, fields in graphQL are nullable. Through adding ! at the of particular fields, we ensure that this field will be non-nullable. It means that if the server resolves field with ! to null, error will be returned, because it failed validation.

How do we query data?

We need to define query type. Query type defines entry point of every query.

type User {
  id: ID!
  name: String!
  email: String!
  age: Int
}

type Query {
  users: [User!]! // again we ensure that field will not return null without throiwing error
}

Then it's time to define resolver. Depending on the tool you use it may look a little differently (I used graphpack). Here's an example:

const fakeDbResponse = [
  { id: 1, name: "John Doe", email: "john@gmail.com", age: 22 },
  { id: 2, name: "Jane Doe", email: "jane@gmail.com", age: 23 },
]
const resolvers = {
  Query: {
    users: () => {
      return fakeDbResponse
    },
  },
}

We can now open graphQL playground and try out if data fetches. Pass this query to playground. As you can see defined resolvers name follows our root query.

query {
  users {
    id
    email
    name
    age
  }
}

The reponse should look like this.

{
  "data": {
    "users": [
      {
        "id": "1",
        "email": "john@gmail.com",
        "name": "John Doe",
        "age": 22
      },
      {
        "id": "2",
        "email": "jane@gmail.com",
        "name": "Jane Doe",
        "age": 23
      }
    ]
  }
}