Using Variables in GraphQL Queries and Mutations

Summary

GraphQL variables let you pass dynamic values separately from the query or mutation text. Instead of embedding values directly in the operation, you declare named variables in the operation signature and supply their values in a separate variables object. This makes scripts reusable and avoids string manipulation when changing input values between runs.

Variable Syntax

Declare a variable in the operation's opening line using a dollar sign and a name, followed by its GraphQL type. Use the variable by name anywhere in the operation where you would otherwise provide a literal value.

The following example queries a repository by name using a variable:

graphql
query GetRepository($name: String!) {
   repository(name: $name) {
      id
      name
      description
   }
}

Supply the variable value as a separate JSON object:

json
{
   "name": "my-repository"
}

The type declaration (String!) is required. The exclamation mark indicates the variable is non-nullable โ€” you must always provide a value. Omit it for optional variables.

Mutations use the same syntax. The following example creates a dashboard using variables for both required fields:

graphql
mutation CreateDashboard($name: String!, $searchDomainName: String!) {
   createDashboard(
      name: $name
      searchDomainName: $searchDomainName
   ) {
      id
      name
   }
}
json
{
   "name": "My Dashboard",
   "searchDomainName": "my-repository"
}

Using Variables in the API Explorer

In the API Explorer, enter variable values in the Query Variables panel below the query editor. Enter them as a JSON object using the same format shown above.

For the repository example, enter the operation in the editor and the following in the Query Variables panel:

json
{
   "name": "my-repository"
}

For more on using the API Explorer, see API Explorer.

Using Variables in Scripts and curl

When using curl or a script, include both a query field and a variables field in the JSON payload:

bash
curl \
   -H "Authorization: Bearer your-api-token" \
   -H "Content-Type: application/json" \
   -X POST \
   https://your-logscale-host/graphql \
   -d '{
      "query": "query GetRepository($name: String!) { repository(name: $name) { id name } }",
      "variables": { "name": "my-repository" }
   }'

For longer operations, read the query text from a separate file to keep scripts readable. For more on scripting with the GraphQL API, see Scripts and curl.