2

I want to create a mutation which takes a dict as an argument. There are implementation-specific reasons to want to do this, instead of creating a type/schema for the dict object.

Object

# types.py
import typing


@strawberry.type
class Thing:
    data: typing.Dict

Resolver

# resolvers.py
import typing
from .types import Thing


def create_config(data: typing.Dict) -> Thing:
    pass

Mutation Schema

# mutations.py
import strawberry

from .types import Thing
from .resolvers import create_thing


@strawberry.type
class Mutations:
    create_thing: Thing = strawberry.mutation(resolver=create_thing)

Desired Example Query

mutation {
    createThing(data: {}) {}
}

From reading the documentation, there's no GraphQL scalar equivalent for a dict. This is evidenced by this compilation error when I try to test:

TypeError: Thing fields cannot be resolved. Unexpected type 'typing.Dict'

My instinct is to flatten the dict into a JSON string and pass it that way. This seems un-elegant, which makes me think there's a more idiomatic approach. Where should I go from here?

Chris
  • 18,724
  • 6
  • 46
  • 80
Inigo Selwood
  • 822
  • 9
  • 20

1 Answers1

4

Instead of a serialized JSON string, JSON itself can be a scalar.

from strawberry.scalars import JSON

@strawberry.type
class Thing:
    data: JSON

def create_config(data: JSON) -> Thing:
    pass
A. Coady
  • 54,452
  • 8
  • 34
  • 40
  • One question here, If I want to pass `{{"key1":"name1"},{"key2":"name2"},{"key3":"name3"}...}` as input without escaping `"` quotes, How it is possible? – siva Jun 04 '23 at 22:38
  • if I follow your approach, i have to escape `"`something like this {{\"key1\":\"name1\"},{\"key2\":\"name2\"},{\"key3\":\"name3\"}...} – siva Jun 04 '23 at 22:40