Intro

A more convenient way to fetch data from API's

  • Instead of 'GET'ing a resource you 'POST' a query that describes what data you want.
  • You think of the data your API returns as a "graph", this allows you to make queries to fetch "related" pieces of data in a single shot. In the example above, you fetch the user and the user's address (as a nested JSON object) in the same API call, as opposed to making 2 API calls.
  • The "query" you send as data in the POST request has a structure and a syntax. This "language" is called GraphQL.

Example Query

query {           |   {
  user (id: 1) {  |     "user": {
    id            |       "id": 1
    name          |       "name": "Elmo"
  }               |     }
}

Benefits

  • Avoid overfetching as specify exactly what data is required
  • Single API calls
  • No need for new API's to be made

GraphQL client-server flow

  • Note that the GraphQL query is not really JSON; it looks like the shape of the JSON you want. So when we make a 'POST' request to send our GraphQL query to the server, it is sent as a "string" by the client.
  • The server gets the JSON object and extracts the query string. As per the GraphQL syntax and the graph data model (GraphQL schema), the server processes and validates the GraphQL query.
  • Just like a typical API server, the GraphQL API server then makes calls to a database or other services to fetch the data that the client requested.
  • The server then takes the data and returns it to the client in a JSON object.

Fetching data

Sample query

query {
   users {
     name
     todos {
       title
     }
   }
 }

Sample query with arguments

query {
  todos(limit: 10) {
    id
    title
  }
}

query {
  users (limit: 1) {
    id
    name
    todos(order_by: {created_at: desc}, limit: 5) {
      id
      title
    }
  }
}

variables

query ($limit: Int!) {
  todos(limit: $limit) {
    id
    title
  }
}

{
   "limit": 10
}

Writing data

Mutation

mutation {
  insert_todos(objects: [{title: "new todo"}]) {
    returning {
      id
    }
  }
}
mutation($todo: todos_insert_input!){
  insert_todos(objects: [$todo]) {
    returning {
      id
    }
  }
}

{
  "todo": {
    "title": "A new dynamic todo"
  }
}

Subscription

GraphQL subscriptions are a way of adding realtime or reactive features to an apps. GraphQL clients and servers that support subscriptions are great because they allow you to build great experiences without having to deal with websocket code!

GraphQL queries/mutations are strings sent to a POST endpoint. A subscription can't happen over a POST endpoint, because a simple HTTP endpoint would just return the response and clsoe the connection.

A GraphQL subscription is a subscription query string sent to a websocket endpoint. And whenever data changes on the backend, new data is pushed over websockets from the server to the client.

subscription {
  online_users {
    id
    last_seen
    user {
      name
    }
  }
}