Input types

Intermediate · 2 min

Use input object types to group arguments into one structured value, with defaults, nested inputs, required fields, and the oneOf directive for either-or input.

Before thisObject types and fieldsNon-null and listsEnums

Also taught inHTML

Jamie Barton · 2 min

Input types

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Jamie BartonReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • An input type, declared with input, is a structured value that a client sends as an argument; it groups related arguments and can grow without changing the field's signature.
  • Input types are not output types: their fields can only be scalars, enums, or other input types, never object types, interfaces, or unions.
  • Input fields can have defaults and can be non-null; the validator rejects missing required fields and unknown fields with clear messages.
  • An omitted input field is absent from the value the server sees, while an explicit null arrives as null, so the two can mean different things.
  • A @oneOf input object requires exactly one of its fields to be set, which models an either-or argument such as lookup by id or by email.

Arguments that outgrow a signature

Suppose books takes a genre, a price ceiling, a minimum year, and some tags. You could list them as separate arguments:

books(genre: String, maxPrice: Float, minYear: Int, tags: [String!]): [Book!]!

That works until you need a second field with the same filter, or a tenth option. Every field repeats the list and every client rebuilds it. A named, reusable value is better. In GraphQL that is an input type:

input BookFilter {
  genre: String
  minYear: Int = 1900
  maxPrice: Float
  tags: [String!]
  range: YearRange
}

input YearRange {
  from: Int!
  to: Int!
}

type Query {
  books(filter: BookFilter, limit: Int): [Book!]!
}

Now books has one filter argument that can gain fields without changing the signature, and BookFilter can be reused by any other field. Inputs are the usual shape for mutations too, which the mutations lesson and designing mutation inputs and payloads develop.

Output types and input types are separate worlds

Why a separate keyword? Output types such as Book can have fields with arguments, resolvers, interfaces and unions. An input value arrives as plain data from a client, so it has to be something JSON can express. GraphQL splits the world in two:

  • Output types: objects, interfaces, unions, scalars, enums.
  • Input types: scalars, enums, and input objects.

Scalars and enums belong to both. You cannot use an object type as an input field. I tried input I { a: A } where A is an object type. buildSchema accepts it, then validateSchema says “The type of I.a must be Input Type but got: A.” So you often end up with Book for output and BookInput for input, with similar-looking fields, and that duplication is deliberate.

What the server sees

I ran books(filter: ...) on graphql-js 17.1.0 with a resolver that prints the argument it received:

{ books(filter: { genre: "sf" }) { title } }
server got: {"genre":"sf","minYear":1900}

The default minYear: 1900 was filled in, because the field was omitted. Now say it explicitly as null:

{ books(filter: { genre: "sf", minYear: null }) { title } }
server got: {"genre":"sf","minYear":null}

The default is not applied. Omitted and null are different. Your resolver can tell them apart, and for update operations that difference matters: omitted often means “leave unchanged” and null means “clear it”.

With variables the client sends the same shape as JSON:

query($f: BookFilter) { books(filter: $f) { title } }
{ "f": { "maxPrice": 10, "range": { "from": 1970, "to": 1980 } } }
server got: {"minYear":1900,"maxPrice":10,"range":{"from":1970,"to":1980}}

Validation

The validator checks inputs before any resolver runs:

{ books(filter: { range: { from: 1970 } }) { title } }
# Expected value of type "YearRange" to include required field "to", found: { from: 1970 }.

{ books(filter: { nope: 1 }) { title } }
# Expected value of type "BookFilter" not to include unknown field "nope", found: { nope: 1 }.

Required fields (! without a default) must be present, and unknown fields are errors. That means your resolver does not need to re-validate shape, only business rules such as “from must be less than to”.

Either-or input with @oneOf

Sometimes an argument is one of several alternatives: find a user by id or by email, never both. The older workaround was a pile of optional fields and a runtime check. Current graphql-js supports @oneOf:

input UserBy @oneOf {
  id: ID
  email: String
}

type Query { user(by: UserBy!): String }

On 17.1.0:

  • user(by: { id: "1" }) is accepted.
  • user(by: { id: "1", email: "a@b.c" }) fails: “Within OneOf Input Object type “UserBy”, exactly one field must be specified, and the value for that field must be non-null.”
  • user(by: {}) fails with the same message.

The fields of a @oneOf input are all nullable in the SDL, and the rule is enforced by the validator, so clients get a clear error and TypeScript generators can produce a union type. Check that your server and client tools are recent enough to support it.

Design hints

  • Name inputs after their purpose and suffix them: BookFilter, CreateBookInput. Tools and humans rely on the suffix.
  • Prefer one input argument over many for anything with more than a couple of options.
  • Keep inputs flat where you can. Deep nesting is hard to write by hand and awkward to evolve.
  • A new optional field is a safe change. A new required field breaks every existing caller.

What the video covers

Jamie Barton’s “GraphQL Input Types” is two and a half minutes, published April 2022. Its description says it shows how to avoid bloating mutations with arguments by using input types you can extend over time, plus naming conventions, how to define them, and using them with variables. That fits the lesson. It is short and I could not read a transcript, so the sections on omitted versus null and @oneOf come from my own runs and are not in the video as far as I know. No other candidate was a better fit, so deeper is empty.

Where this fits

That completes the type system: scalars, objects, lists, enums, interfaces, unions, and inputs. Now you can use it. The next group is about writing queries against such a schema. Next: fields and selection sets.

Check yourself

  1. 01Why not just add more arguments to the field instead of using an input type?

    An input type groups related values into one named argument, can be reused across fields and nested, and lets you add optional fields later without changing the field's signature.

  2. 02Can an input type have a field whose type is an object type?

    No. Input fields must be input types, meaning scalars, enums, or other input objects, and validateSchema reports that the type must be an Input Type.

  3. 03How does the server tell an omitted field from one set to null?

    An omitted field is absent from the argument object, while an explicit null is present with the value null, and a default applies only when the field is omitted.

  4. 04What does @oneOf do?

    It makes the validator require that exactly one field of the input object is provided and non-null.

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark