0

Is there a lib/tool for Python to automatically parse a graphqls file? If not, what is a good way to parse the file?

I have a Python project that is part of a larger Java project that contains a .graphqls file with the enum, input, and type definitions.

For example, the file has:

enum Version {
   A
   B
}

input ProjInput {
   name: String!
   term: String
   version: Version
}

type ProjType {
   name: String
   term: String
   version: Version
}

The file also contains the queries and mutations:

type Query {
   queryProj(projName: String!): ProjType
}

type Mutation {
   addProj(projInput: ProjInput): ProjType
}

I looked around but I can't find a tool to parse this data into a dict (or some other type) in Python. It would be nice to just do something like parsing json with json.loads(). Does such a lib/tool exist? And if not, how can I parse this file myself?

I can open and read the file, I am just not sure if just reading it line-by-line is a good method, or if I can automatically read enum types, for example.

Ebad
  • 131
  • 11

1 Answers1

0

You can parse graphql schema file, inspect it, and print the schema details as a dictionary in JSON-like format using 'graphql-core-next' library . However it doesn't handle the queries and mutations. You need to investigate further to cover that part using more advanced library.

assuming that u have installed the library using

pip install graphql-core-next

You can use below method to try it out

from graphql import build_ast_schema, parse
import json

def parse_graphqls_file(file_path):
    with open(file_path, 'r') as file:
        schema_ast = parse(file.read())
    return build_ast_schema(schema_ast)

file_path = 'location/of/graphqls/file'
schema = parse_graphqls_file(file_path)

# To inspect and get the schema details as a dictionary
schema_dict = {}
for type_name, graphql_type in schema.type_map.items():
    if not type_name.startswith("__"):
        schema_dict[type_name] = {
            "kind": graphql_type.__class__.__name__,
            "fields": {
                field_name: {
                    "type": str(field.type),
                    "required": not field.type.is_nullable
                }
                for field_name, field in graphql_type.fields.items()
            }
        }

print(json.dumps(schema_dict, indent=2))
  • Thank you. I will give this a try. Though if it can't do the queries and mutations, I might need to write my own. Thanks! – Ebad Jul 29 '23 at 02:16