Igor Zaliznyak
Igor Zaliznyak

Reputation: 63

How to get GraphQL schema with Python?

There's lots of GUI clients like GraphQL Playground, GraphiQl, etc. with ability of getting GraphQL schema from the URL. How can I get the schema with Python?

Upvotes: 6

Views: 6516

Answers (5)

MedMJ
MedMJ

Reputation: 1

I was having the same problem until I came across the answer in the python graphql repo, you can use this code snippet example to get the schema and save it in a .json file

async def get_graphql_schema(endpoint, api_key):
    headers = {"X-API-KEY": api_key}
    transport = AIOHTTPTransport(url=endpoint, headers=headers)
    async with Client(transport=transport, fetch_schema_from_transport=True) as session:
        query_intros = get_introspection_query(descriptions=True)
        query = gql(query_intros)
        intros_result = await session.execute(query)
        schema = build_client_schema(intros_result)
        return schema

def save_schema_to_json(schema):
    schema_dict = introspection_from_schema(schema)
    output_file = 'schema.json'
    with open(output_file, 'w') as json_file:
        dump(schema_dict, json_file, indent=2)

schema = asyncio.run(get_graphql_schema(env_dev['url'], env_dev['key']))
save_schema_to_json(schema)

What you are looking for is introspection_from_schema() and I quote its documentation in the source code :

Build an IntrospectionQuery from a GraphQLSchema

IntrospectionQuery is useful for utilities that care about type and field relationships, but do not need to traverse through those relationships.

This is the inverse of build_client_schema. The primary use case is outside of the server context, for instance when doing schema comparisons.

Upvotes: 0

Sofi
Sofi

Reputation: 51

You can use sqglc library, introspection module.

1. Creates a json schema file:

python3 -m sgqlc.introspection --exclude-deprecated --include-description ****-H "Authorization: Bearer {TOKEN}" http://yourgrapqlservice.com schema.json

--exclude-deprecated If given, will exclude deprecated fields and enumeration values.

Default: False

--exclude-description If given, will exclude description (documentation).

2. Converts the schema to .py format if needed:

sgqlc-codegen schema schema1.json schema.py

Upvotes: 0

Vaibhav Rai
Vaibhav Rai

Reputation: 183

This will create a json file with your schema.

import json

introspection_dict = your_schema_object.introspect()

# Or save the schema into some file
with open("schema.json", "w") as fp:
    json.dump(introspection_dict, fp)

Upvotes: 0

minghua
minghua

Reputation: 6613

The graphql-core has utilities to get you the query, and convert the query result. Here is an example snippet that print the resulting schema in sdl:

from graphqlclient import GraphQLClient
from pprint import PrettyPrinter
from graphql import get_introspection_query, build_client_schema, print_schema

def main():
    pp = PrettyPrinter(indent=4)
    client = GraphQLClient('http://swapi.graph.cool/')
    query_intros = get_introspection_query(descriptions=True)
    intros_result = client.execute(query_intros, variables=None, operationName=None)
    client_schema = build_client_schema(intros_result.get('data', None))
    sdl = print_schema(client_schema)
    print(sdl)
    pp.pprint(sdl)

I was looking for the same and found the above in the end.

Upvotes: 2

Daniel Rearden
Daniel Rearden

Reputation: 84837

From the spec:

A GraphQL server supports introspection over its schema. This schema is queried using GraphQL itself, creating a powerful platform for tool‐building... The schema introspection system is accessible from the meta‐fields __schema and __type which are accessible from the type of the root of a query operation.

Tools like GraphQL Playground and GraphiQL utilize introspection to get information about a schema. You don't need any additional tools or libraries to make an introspection query -- since it's just a GraphQL query, you'll make the request the same way you make any other request to the endpoint (using requests for example).

Here's a complete introspection query from 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
                }
              }
            }
          }
        }
      }
    }
  }
"""

Upvotes: 8

Related Questions