Schema
GraphQL Input Types
Defining Input Types
GraphQL input types specify mutation input structures.
What are GraphQL Input Types?
In GraphQL, input types are a special kind of type that allows you to define the structure of inputs for mutations. They are similar to object types, but they are meant to be used as parameters for mutations rather than as return types. Input types help ensure that clients provide all necessary information in a structured manner when making changes to the data.
Defining Input Types
Input types are defined using the input
keyword, which is followed by the name of the input type. Within the input type definition, fields are specified along with their data types. These fields can include scalars, enums, and even other input types, but they cannot include object types or interface types.
Using Input Types in Mutations
Once an input type is defined, it can be used in a mutation to specify the expected input structure. This ensures that the mutation receives all necessary fields in the correct format. Below is an example of how an input type can be used in a mutation.
Benefits of Using Input Types
- Validation: Input types automatically enforce the required fields and their types, reducing the risk of errors.
- Reusability: Once defined, input types can be reused across different mutations, promoting consistency.
- Clarity: They provide a clear contract for the inputs expected by mutations, improving the understanding and documentation of your API.
Example: Complete Mutation with Input Type
Let's put it all together with a complete example that includes a mutation using an input type. This mutation will create a new user in the system.
In this example, the CreateUserInput
input type is used in the createUser
mutation. This setup ensures the mutation receives the necessary information to create a user, and it returns the newly created User
object.