How to Pass Input Object to Mutation in GraphQL
To pass an input object to a GraphQL mutation, define an
input type in your schema and use it as an argument in the mutation. Then, send the input object as a variable or inline argument when calling the mutation.Syntax
Define an input type to group related fields. Use this input type as an argument in your mutation definition. When calling the mutation, pass the input object with matching fields.
- input type: groups fields for input
- mutation argument: uses the input type
- mutation call: passes the input object
graphql
input UserInput {
name: String!
email: String!
age: Int
}
type Mutation {
createUser(input: UserInput!): User
}Example
This example shows a mutation createUser that takes a UserInput object. The mutation is called with variables to pass the input object.
graphql
# Schema definition
input UserInput {
name: String!
email: String!
age: Int
}
type User {
id: ID!
name: String!
email: String!
age: Int
}
type Mutation {
createUser(input: UserInput!): User
}
# Mutation query with variables
mutation CreateUser($input: UserInput!) {
createUser(input: $input) {
id
name
email
age
}
}
# Variables JSON
{
"input": {
"name": "Alice",
"email": "alice@example.com",
"age": 30
}
}Output
{
"data": {
"createUser": {
"id": "1",
"name": "Alice",
"email": "alice@example.com",
"age": 30
}
}
}
Common Pitfalls
Common mistakes include:
- Not defining an
inputtype and trying to usetypeinstead. - Passing fields that do not match the input type structure.
- Forgetting to mark the input argument as non-nullable (
!) if required. - Not using variables and trying to pass complex objects inline incorrectly.
graphql
# Wrong: Using type instead of input # This will cause schema errors type UserInput { name: String! email: String! } # Right: Use input keyword input UserInput { name: String! email: String! }
Quick Reference
| Step | Description | Example |
|---|---|---|
| 1 | Define input type | input UserInput { name: String! email: String! age: Int } |
| 2 | Use input type in mutation | createUser(input: UserInput!): User |
| 3 | Call mutation with input object | mutation ($input: UserInput!) { createUser(input: $input) { id name } } |
| 4 | Pass variables matching input | { "input": { "name": "Alice", "email": "a@b.com" } } |
Key Takeaways
Always define an input type to group mutation input fields.
Pass the input object as a variable matching the input type structure.
Use the
input keyword, not type, for input objects.Mark required input arguments with
! to enforce validation.Avoid passing complex objects inline; use variables for clarity and correctness.