| 1 |
Using an Introspection Query |
| 2 |
---------------------------- |
| 3 |
|
| 4 |
.. currentmodule:: graphql.utilities |
| 5 |
|
| 6 |
A third way of building a schema is using an introspection query on an existing server. |
| 7 |
This is what GraphiQL uses to get information about the schema on the remote server. |
| 8 |
You can create an introspection query using GraphQL-core 3 with the |
| 9 |
:func:`get_introspection_query` function:: |
| 10 |
|
| 11 |
from graphql import get_introspection_query |
| 12 |
|
| 13 |
query = get_introspection_query(descriptions=True) |
| 14 |
|
| 15 |
This will also yield the descriptions of the introspected schema fields. You can also |
| 16 |
create a query that omits the descriptions with:: |
| 17 |
|
| 18 |
query = get_introspection_query(descriptions=False) |
| 19 |
|
| 20 |
In practice you would run this query against a remote server, but we can also run it |
| 21 |
against the schema we have just built above:: |
| 22 |
|
| 23 |
from graphql import graphql_sync |
| 24 |
|
| 25 |
introspection_query_result = graphql_sync(schema, query) |
| 26 |
|
| 27 |
The ``data`` attribute of the introspection query result now gives us a dictionary, |
| 28 |
which constitutes a third way of describing a GraphQL schema:: |
| 29 |
|
| 30 |
{'__schema': { |
| 31 |
'queryType': {'name': 'Query', 'kind': 'OBJECT'}, |
| 32 |
'mutationType': None, 'subscriptionType': None, |
| 33 |
'types': [ |
| 34 |
{'kind': 'OBJECT', 'name': 'Query', 'description': None, |
| 35 |
'fields': [{ |
| 36 |
'name': 'hero', 'description': None, |
| 37 |
'args': [{'name': 'episode', 'description': ... }], |
| 38 |
... }, ... ], ... }, |
| 39 |
... ], |
| 40 |
... } |
| 41 |
} |
| 42 |
|
| 43 |
This result contains all the information that is available in the SDL description of the |
| 44 |
schema, i.e. it does not contain the resolve functions and information on the |
| 45 |
server-side values of the enum types. |
| 46 |
|
| 47 |
You can convert the introspection result into ``GraphQLSchema`` with GraphQL-core 3 by |
| 48 |
using the :func:`build_client_schema` function:: |
| 49 |
|
| 50 |
from graphql import build_client_schema |
| 51 |
|
| 52 |
client_schema = build_client_schema(introspection_query_result.data) |
| 53 |
|
| 54 |
|
| 55 |
It is also possible to convert the result to SDL with GraphQL-core 3 by using the |
| 56 |
:func:`print_schema` function:: |
| 57 |
|
| 58 |
from graphql import print_schema |
| 59 |
|
| 60 |
sdl = print_schema(client_schema) |
| 61 |
print(sdl) |
| 62 |
|
| 63 |
This prints the SDL representation of the schema that we started with. |
| 64 |
|
| 65 |
As you see, it is easy to convert between the three forms of representing a GraphQL |
| 66 |
schema in GraphQL-core 3 using the :mod:`graphql.utilities` module. |