Skip to content

Use variables

Igor Dianov edited this page May 29, 2024 · 2 revisions

In order to make a query re-usable, it can be made dynamic by using variables. Just like a REST API, it is possible to pass variable arguments to an endpoint in a GraphQL API. By declaring the arguments in the query defintion, typechecking happens automatically. Each variable argument must be named with $ prefix and have a type. To use variable inside query, simply reference it in any criteria expressions. Each variable reference will be resolved to its value during query execution, for example:

Example: Fetch an author by their authors id:

query booksByAuthorId($authorId: Long!) {
  Books(
    where: { author: {id: {EQ: $authorId  } } }
  ) {
    select {
      id
      title
    }
  }
}

Variables:

{
  "authorId": 1
}

Result:

{
  "data": {
    "Books": {
      "select": [
        {
          "id": 2,
          "title": "War and Peace"
        },
        {
          "id": 3,
          "title": "Anna Karenina"
        }
      ]
    }
  }
}