How to define an empty Object Type in a GraphQL schema?

How to define an empty Object Type in a GraphQL schema?


9

I want to specify my GraphQL API in a schema, but I also want to spread my schema out among multiple files. I want to be able to use extend type Query or extend type Mutation to add queries or mutations to the overall schema. For example, my user.graphql file is as follows:

type User {
    id: ID!
    name: String!
    email: String!
}

type UserResult {
    success: Boolean!
    errors: [String]
    user: User
}

extend type Query {
    user(userId: ID!): UserResult!
}

The Query Object Type is defined in a different file, schema.graphql:

schema {
    query: Query
    mutation: Mutation
}

type Query {
    dummyField: Boolean
}

These files are combined when my application launches to produce the full API schema.

For type Query I have included a dummyField because I can’t define an empty Object Type (one without fields) without getting an error. The following lines:

type Query {}

and

type Query {
}

Throw errors like:

line 988, in expect_token f"Expected {get_token_kind_desc(kind)},
found {get_token_desc(token)}.",
graphql.error.syntax_error.GraphQLSyntaxError: Syntax Error: Expected
Name, found ‘}’.

I would prefer for these Object Types to be empty to avoid the dummyField polluting my code and to make it clear that the intention is for Query and Mutation to be extended in other files.

I am using Flask with ariadne (0.13.0), which relies on graphql-core (3.1.5). I could not find anything in the most recent GraphQL specification about empty Object Types. Is it possible to declare empty Object Types in the schema, without using a placeholder field? If so, what is the correct syntax?

1 Answer
1


16

After some digging I found this GitHub Issue Comment with the following syntax:

type Query

extend type Query {
  a: Boolean;
}

I applied this to the examples above and they worked.
Therefore, to create an empty Object Type, omit the curly braces { ... }.

The GraphQL specification here indicates that the ObjectTypeDefinition‘s FieldsDefinition is optional, although this is not abundantly clear.

How to define an empty Object Type in a GraphQL schema?

1

  • 5

    Just to clarify for future readers, there seems to be a bit of confusion in the spec around this, as there are other Type Validation sections that require types to define at least one field (spec.graphql.org/October2021/#sel-FAHZhCFDBAACDA4qe). Also, other libraries such as sangria and graphql-java don't support empty types like shown in this example.

    – Logan

    Oct 10, 2022 at 20:57




Leave a Reply

Your email address will not be published. Required fields are marked *