Introduction
GraphQL is a query language we use for our API. The advantage of using GraphQL over other methods is it allows us to request only the data we need. All requests are made through a single endpoint by sending a query string along with variables to specify exactly what data is required.
Queries and Mutations
Requests are divided into two types: Queries
and Mutations
. By convention, queries are used for requesting data, and mutations are used to write data. To see how queries and mutations are structured, let’s look at an example of a query.
{ user { xcoobee_id user_type first_name last_name } }
In this example, we are querying the user field and requesting several types of data from the user. For more information about GraphQL, visit the documentation here.
XcooBee GraphQL
There are certain features of the our GraphQL implementation that cannot be found in the general documentation. Let’s see what those features are.
Cursors
Cursors are opaque object references that can be used to refer to things like Bees, Users, and Transactions. These are often used for pagination.
Connections
We use a connection when we want to return something other than a single object. For example, when we want to return multiple users from the users query, we request the data field of the userConnection
with the types of data we need from those users. We can also get pagination information from connections. The page_info
field returns an end_cursor
and has_next_page
.
An end_cursor
points to the final object on a page. It can be passed to the after parameter to get the next page of data.
Note: This cursor can only be used for pagination.
has_next_page
lets you know whether there is another page to be requested.
A user connection might also return total_count
which lets you know the total number of objects that can be returned from a query. This can allow you to determine the number of pages without having to rely on has_next_page
.
Example
We can see how cursors and connections work by looking at an example of a query that uses both.
query balances ($user_cursor: String! $first: Int) { balances (user_cursor: $user_cursor, first: $first) { data { type currency date } page_info { has_next_page } } }
In this example we are using user_cursor
to refer to the user that whose balances we are requesting.
We are requesting the data field with the fields we are looking for: type
, currency
, and date
. We also are requesting info about whether there is another page to fetch.
For example, if we passed 5
into the first argument, we would return up to five balances. If a user had four balances, the first four balances would be returned and has_next_page
would be false. Instead, if a user had six balances then five balances would be returned, and has_next_page
would return true.