graphql-core graphql_sync(schema, {'query': ..., 'variables': ...}) raises 'KeyError: 0' in lexer.py read_next_token (char = body[position]): ariadne vs graphql-core signature mix-up
Symptom: executing a test query against a locally built schema (an SDL rebuilt for the Matterport Model API, used to mock the HackPrinceton quickstart queries) with
from graphql import build_schema, graphql_sync
result = graphql_sync(schema, {"query": test_query, "variables": {"id": "zvKHR9DHNjJ"}})fails deep inside the parser: graphql/language/parser.py ... parse_document -> lexer.py, line 184, in read_next_token: char = body[position] # SourceCharacter -> KeyError: 0. Validation with parse() + validate() passed a moment earlier, so it looks like a schema problem. It isn't.
Cause: two libraries export a function named graphql_sync with different signatures. ariadne's ariadne.graphql_sync(schema, data, ...) takes the whole request dict and returns a (success, result_dict) tuple. That's the form in every ariadne Flask example. graphql-core's graphql.graphql_sync(schema, source, root_value=None, context_value=None, variable_values=None, operation_name=None, ...) expects the query string as the second argument. Passing a dict there makes the lexer index body[0] on a dict, hence KeyError: 0. Reproduced with graphql-core 3.3.2.
Fix (graphql-core):
result = graphql_sync(schema, test_query, root_value=mock_root, variable_values={"id": "zvKHR9DHNjJ"})
print(result.data, result.errors) # ExecutionResultor, if you really want ariadne's request-dict style, import it from ariadne and use an executable schema:
from ariadne import make_executable_schema, graphql_sync
ok, result = graphql_sync(make_executable_schema(sdl, query_type), {"query": q, "variables": v})Note that a plain build_schema() schema has no resolvers, so graphql-core falls back to the default resolver: pass a root_value dict shaped like the response (for example {'model': lambda info, id: {...}} or nested dicts) to get data back instead of None.
Verify: graphql_sync(build_schema('type Query { a: String }'), '{ a }', root_value={'a': 'x'}) returns ExecutionResult(data={'a': 'x'}, errors=None), while the dict form reproduces KeyError 0.