Input Object Types

We already looked at arguments, which allow us to use simple scalars like String to pass data into a field. GraphQL defines input object types to allow us to use objects as arguments on our fields.

Input object type definitions differ from object types only in the used keyword and in that their fields can not have arguments.

SDL
input BookInput {
title: String
author: String
}

Usage

Input object types can be defined like the following.

C#
public class BookInput
{
public string Title { get; set; }
public string Author { get; set; }
}
public class Mutation
{
public async Task<Book> AddBook(BookInput input)
{
// Omitted code for brevity
}
}

Note: If a class is used as an argument to a resolver and it does not end in Input, Hot Chocolate (by default) will append Input to the type name in the resulting schema.

We can also use a class both as an output- and an input-type.

C#
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
}
public class Mutation
{
public async Task<Book> AddBook(Book input)
{
// Omitted code for brevity
}
}

This will produce the following schema.

SDL
type Book {
title: String
author: String
}
input BookInput {
title: String
author: String
}
type Mutation {
addBook(input: BookInput): Book
}

Note: While it is possible, it is not encouraged, as it complicates future extensions of either type.

Immutable types

If we want our input type classes to be immutable, or we are using nullable reference types, we can provide a non-empty constructor and Hot Chocolate will instead use that when instantiating the input. Just note that

  1. The type of the argument must exactly match the property's type
  2. The name of the argument must match the property name (bar a lowercase first letter)
  3. No setters will be called, so you need to provide arguments for all the properties.

Hot Chocolate validates any custom input constructor at schema build time, so we don't need to worry about breaking things during refactoring!

C#
public class BookInput
{
// No need for the setters now
public string Title { get; }
public string Author { get; }
public BookingInput(string title, string author)
{
Title = title;
Author = author;
}
}

We can also use record types, if we're on C# 9.0+. The equivalent to the above would be:

C#
public record BookingInput(string Title, string Author);