graphene/docs/pages/guide/mutation.md
2015-11-25 11:23:31 -08:00

1.3 KiB

Mutations

A Mutation is a special ObjectType that define also an Input.

Quick example

This example model defines a Mutation:

import graphene

class CreatePerson(graphene.Mutation):
	class Input:
		name = graphene.String()

    ok = graphene.String()
    person = graphene.Field('Person')

    @classmethod
    def mutate(cls, args, info):
    	person = Person(name=args.get('name'))
    	ok = True
    	return CreatePerson(person=person, ok=ok)

person and ok are the output fields of the Mutation when is resolved. Input attributes are the arguments that the Mutation needs for resolving. mutate is the function that will be applied once the mutation is called.

So, we can finish our schema like this:

# ... the Mutation Class

class Person(graphene.ObjectType):
	name = graphene.String()

class MyMutations(graphene.ObjectType):
	create_person = graphene.Field(CreatePerson)

schema = graphene.Schema(mutation=MyMutations)

Executing the Mutation

Then, if we query (schema.execute(query_str)) the following:

mutation myFirstMutation {
	createPerson(name:"Peter") {
		person {
			name
		}
		ok
	}
}

We should receive:

{
	"createPerson": {
		"person" : {
			name: "Peter"
		},
		"ok": true
	}
}