Convert GraphQLResponse dictionary to python object

Viewed 90

I am running a graphql query using aiographql-client and getting back a GraphQLResponse object, which contains a raw dict as part of the response json data.

This dictionary conforms to a schema, which I am able to parse into a graphql.type.schema.GraphQLSchema type using graphql-core's build_schema method.

I can also correctly get the GraphQLObjectType of the object that is being returned, however I am not sure how to properly deserialize the dictionary into a python object with all the appropriate fields, using the GraphQLObjectType as a reference.

Any help would be greatly appreciated!

1 Answers

I'd recommend using Pydantic to the heavy lifting in the parsing. You can then either generate the models beforehand and select the ones you need based on GraphQLObjectType or generate them at runtime based on the definition returned by build_schema.

If you really must define your models at runtime you can do that with pydantic's create_model function described here : https://pydantic-docs.helpmanual.io/usage/models/#dynamic-model-creation

For the static model generation you can probably leverage something like https://jsontopydantic.com/

If you share some code samples I'd be happy to give some more insights on the actual implementation

Related