Home > Mobile >  Convert snake_case to camelCase in Python GraphQL resolver using Ariadne
Convert snake_case to camelCase in Python GraphQL resolver using Ariadne

Time:05-30

I have created a Python Flask server with Apollo GraphQL using Ariadne. My GraphQL schema should have attributes names in camelCase. However, it seems like, it is must for my GraphQL resolver to return attributes names in snake_case or else the response doesn't get resolved.

Here is my GraphQL schema definition:

type Asset {
    assetId: ID!
    accountId: Int
    version
}

type Query {
    getAssets() : [Asset]
}

My resolver function:

@convert_kwargs_to_snake_case
def get_commercial_asset_resolver(obj, info):
    """Resolver function to fetch list of assets"""        
    assets = runquery.run_query_for_assets()
    return assets

With decorator @convert_kwargs_to_snake_case in place, one attribute gets mapped successfully in the GraphQL response i.e. version as snake_case and camelCase for it is same.

However, if I remove @convert_kwargs_to_snake_case from my resolver, none of the attributes from my result set gets mapped to the GraphQL response.

Is it possible to user camelCase attributes with Ariadne in Python? By looking at Ariadne documentation it seems like it's not. Looking for suggestions.

CodePudding user response:

Well, after reading this Ariadne discussion, I figured out that, I just had not to pass Ariadne snake_case_fallback_resolvers while creating Ariadne executable GraphQL schema.

So, basically, what I had done was -

from ariadne import load_schema_from_path, make_executable_schema, snake_case_fallback_resolvers, graphql_sync, ObjectType

type_defs = load_schema_from_path("./schema.graphql")
schema = make_executable_schema(type_defs, query, snake_case_fallback_resolvers)

What I did to fix this issue of not being able to map attributes in camelCase back to GraphQL response:

schema = make_executable_schema(type_defs, query)
# Just removed snake_case_fallback_resolvers from the function parameters

Also, I removed @snake_case_fallback_resolvers from the resolver function, to get attributes if any passed as input to the resolver in camelCase.

  • Related