How to get GraphQL schema with Python?

How to get GraphQL schema with Python?


6

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?

5 Answers
5


7

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
                }
              }
            }
          }
        }
      }
    }
  }
"""

1

  • thanks a lot, this query works and returns all the fields!

    – Igor Zaliznyak

    Dec 11, 2018 at 17:15


1

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('https://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.

3

  • 1

    This gives me the following error: TypeError: execute() got an unexpected keyword argument 'operationName'

    – lateus

    Sep 7, 2021 at 17:29

  • Ok. Just take out the "operationName=None" from the call. It works on "graphql.org/swapi-graphql". It works with the intro_result. But the next line creating schema will fail, need to replace "data" element with a valid one. The environment: python 3.8, graphql-core 3.0.3, graphqlclient 0.2.4, urllib3 1.25.8. You can pick a public api from github.com/APIs-guru/graphql-apis

    – minghua

    Nov 2, 2021 at 15:54


  • Got method not allowed. Tried a few other links, each gives a different error. Not sure.

    – minghua

    Nov 2, 2021 at 16:11


0

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)


0

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}" https://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


0

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.



Leave a Reply

Your email address will not be published. Required fields are marked *