如何使用 Python 获取 GraphQL 模式?

Igo*_*yak 4 python python-3.x python-requests graphql

有很多 GUI 客户端,如 GraphQL Playground、GraphiQl 等,能够从 URL 获取 GraphQL 模式。如何使用 Python 获取模式?

Dan*_*den 6

从规范:

GraphQL 服务器支持对其架构进行自省。该模式使用 GraphQL 本身进行查询,为工具构建创建了一个强大的平台...模式内省系统可以从元字段 __schema 和 __type 访问,这些字段可以从查询操作的根类型访问。

GraphQL Playground 和 GraphiQL 等工具利用自省来获取有关模式的信息。您不需要任何额外的工具或库来进行自省查询——因为它只是一个 GraphQL 查询,您将像向端点发出任何其他请求一样发出请求(requests例如使用)。

这是一个完整的自省查询graphql-core:

introspection_query = """
  query IntrospectionQuery {
    __schema {
      queryType { name }
      mutationType { name }
      subscriptionType { name }
      types {
        ...FullType
      }
      directives {
        name
        description
        locations
        args {
          ...InputValue
        }
      }
    }
  }
  fragment FullType on __Type {
    kind
    name
    description
    fields(includeDeprecated: true) {
      name
      description
      args {
        ...InputValue
      }
      type {
        ...TypeRef
      }
      isDeprecated
      deprecationReason
    }
    inputFields {
      ...InputValue
    }
    interfaces {
      ...TypeRef
    }
    enumValues(includeDeprecated: true) {
      name
      description
      isDeprecated
      deprecationReason
    }
    possibleTypes {
      ...TypeRef
    }
  }
  fragment InputValue on __InputValue {
    name
    description
    type { ...TypeRef }
    defaultValue
  }
  fragment TypeRef on __Type {
    kind
    name
    ofType {
      kind
      name
      ofType {
        kind
        name
        ofType {
          kind
          name
          ofType {
            kind
            name
            ofType {
              kind
              name
              ofType {
                kind
                name
                ofType {
                  kind
                  name
                }
              }
            }
          }
        }
      }
    }
  }
"""
Run Code Online (Sandbox Code Playgroud)