Getting started with GraphQL from the console or the command line
GraphQL is a standard for defining, querying and documenting APIs in a human-friendly way, with built-in documentation, a friendly query language and a bunch of tools to help you get started.
This guide shows you how to query the GraphQL API using the GraphQL console and from the command line. You'll first need a Buildkite account, and a Buildkite API Access Token with GraphQL scope.
Running your first GraphQL request in the console
The following is a GraphQL query that requests the name of the current user (the account attached to the API Access Token, in other words, you!)
query {
viewer {
user {
name
}
}
}
Running that in the GraphQL console returns:
{
"data": {
"viewer": {
"user": {
"name": "Sam Wright"
}
}
}
}
Notice how the structure of the data returned is similar to the structure of the query.
Running your first GraphQL request on the command line
To run the same query using cURL, replace xxxxxxx
with your API Access Token:
$ curl 'https://graphql.buildkite.com/v1' \
-H 'Authorization: Bearer xxxxxxx' \
-H "Content-Type: application/json" \
-d '{
"query": "query { viewer { user { name } } }"
}'
which returns exactly the same as the query we ran in the explorer:
{
"data": {
"viewer": {
"user": {
"name": "Sam Wright"
}
}
}
}
Getting collections of objects
Getting the name of the current user is one thing, but what about a more complex query?
The builds
field of the user
returns a BuildConnection
.
A connection is a collection of objects, and requires some metadata called edges
and nodes
.
In the this query we're asking for for the current user's most recently created build (get one build, starting from the first first): 1
).
query {
viewer {
user {
name
builds(first: 1) {
edges {
node {
number
branch
message
}
}
}
}
}
}
which returns:
{
"data": {
"viewer": {
"user": {
"name": "Sam Wright",
"builds": {
"edges": [
{
"node": {
"number": 136,
"branch": "main",
"message": "Merge pull request #796 from buildkite/docs\n\nImprove API docs"
}
}
]
}
}
}
}
}