41

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.

Robert Zaremba
  • 8,081
  • 7
  • 47
  • 78
  • 2
    There's a GraphQL bug that makes it [fail to parse `users()` as a valid query](https://github.com/graphql/graphql-js/issues/1860), even though the `n` parameter is optional. You're forced to write `users` if all parameters are missing. – Dan Dascalescu May 12 '19 at 22:24

1 Answers1

70

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
    }
  }
}
Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • What about a [query with one optional parameter](https://github.com/graphql/graphql-js/issues/1860)? How should that be defined so that both `users(n: 100)` and `users()` are valid? – Dan Dascalescu May 12 '19 at 22:25
  • Arguments are nullable by default. The latter will never be valid because it's invalid syntax. If you don't pass in any arguments, you need to omit the parentheses. – Daniel Rearden May 12 '19 at 23:07