How to correctly declare a GraphQL query without parameters.

Robert Zaremba picture Robert Zaremba · Oct 12, 2018 · Viewed 8.9k times · Source

I'm using vs code + graphql-cli for validating & linting the schema. In the following declaration (in the graphql schema file):

type Query {
  users(): Int
}

The users declaration above is marked as en error, but it doesn't make any problem (or warning) by the server - it's only vs code and graphql lint reporting it as an error:

2:9 Syntax Error: Expected Name, found )  undefined

If I add a parameter to the query, eg:

type Query {
  users(n: Int): Int
}

then there is no problem reported by vs code or graphql-cli. How can I properly declare a graphql query without parameters.

Answer

Daniel Rearden picture Daniel Rearden · Oct 12, 2018

The queries you specify in your schema behave just like any other field on a particular type (the main difference is that their type is linked to a particular operation). If you don't want to declare any arguments for a particular field, you just omit the parentheses entirely. The same goes for queries and mutations:

type Query {
  users: Int
}

From the spec:

Fields are conceptually functions which return values, and occasionally accept arguments which alter their behavior. These arguments often map directly to function arguments within a GraphQL server’s implementation.

So it's worthwhile pointing out that any Type's field could have arguments. For example, a query could look like this:

query UsersQuery {
  users {
    name
    posts (onlyNew: true) {
      title
    }
  }
}