graphqlflask-graphql

How can I extract data from a list of dicts using graphene's mutation method?


I’m trying to created a list of objects using graphql mutation, but have been unsuccessful. I've identified the error, please see code snippets and comment on where the error is propagating.

Note: I'm using Graphene on Flask with Python 2.7

Here’s an example payload:

mutation UserMutation {
    createUser(
        phones: [
            {
                “number”: “609-777-7777”,
                “label”: “home"   
            },
            {
                “number”: “609-777-7778”,
                “label”: “mobile"   
            }
        ]
    )
}

On the schema, I have the following:

class CreateUser(graphene.Mutation):
    ok = graphene.Boolean()
    ...
    phones = graphene.List(graphene.String())  # this is a list of string but what I need is a list of dicts!

Solution

  • For having a dict as a Input, you need to use InputObjectType. (InputObjectTypes are like ObjectTypes but just for input data).

    This example should work with graphene 1.0.

    class PhoneInput(graphene.InputObjectType):
        number = graphene.String()
        label = graphene.String()
    
    class CreateUser(graphene.Mutation):
        class Input:
            phones = graphene.List(PhoneInput)
        ok = graphene.Boolean()
    
    class Mutation(graphene.ObjectType):
        create_user = CreateUser.Field()