GraphQL查询与Schema校验问题求助:校验函数未正常生效
解决GraphQL查询与Schema校验问题
问题根源
你当前代码的核心问题是:validate 函数接收的第一个参数必须是 GraphQLSchema 实例,但你直接传入了从AppSync获取的原始自省(introspection)JSON数据,导致校验逻辑无法正确解析Schema结构,自然没法校验字段合法性。
修正方案
使用 graphql.build_client_schema 把自省JSON转换成标准的 GraphQLSchema 对象,再配合正确的查询解析方式,就能实现完整的字段合法性校验。
修正后的代码:
import json import boto3 from graphql import build_client_schema, parse, validate # 创建AppSync客户端 client = boto3.client( 'appsync', aws_access_key_id='xxx', aws_secret_access_key='xxx', aws_session_token=aws_session_token, region_name=region ) # 获取自省Schema response = client.get_introspection_schema( apiId='API ID', format='JSON', includeDirectives=True ) response_data = response['schema'].read().decode('utf-8') introspection_data = json.loads(response_data) # 从自省数据构建GraphQLSchema实例 schema = build_client_schema(introspection_data) # 待校验的查询 query_to_validate = '''query MyQuery { indicatorsConnection(first: 10, groupIds: "somedataofids") { edges{ node{ id orientation } } } }''' # 解析查询为AST query_ast = parse(query_to_validate) # 执行校验 errors = validate(schema, query_ast) if errors: print("查询不合法:") for error in errors: # 把英文错误信息转成中文 error_msg = error.message.replace('Field', '字段')\ .replace('type', '类型')\ .replace('cannot be queried', '无法被查询')\ .replace('Unknown field', '未知字段')\ .replace('Argument', '参数')\ .replace('has invalid value', '值不合法') print(f"错误位置:{error.locations},信息:{error_msg}") else: print("查询合法。")
其他可行校验方案
- 使用最新版GraphQL-Core:确保安装v3+版本,它包含所有标准校验规则,覆盖字段存在性、参数类型匹配、必填字段检查等场景。
- 本地SDL文件校验:如果能获取AppSync的SDL(Schema定义语言)文件,直接用
build_schema从SDL构建Schema,比自省JSON更直观,校验效率更高。 - AppSync服务端校验:开发阶段可将查询发送到AppSync测试端点,利用服务端原生Schema做校验,但这种方式依赖网络,适合最终验证而非本地开发。
内容的提问来源于stack exchange,提问作者Vishruth
相关产品推荐
相关产品推荐

