| 1 |
Using the Schema Definition Language |
| 2 |
------------------------------------ |
| 3 |
|
| 4 |
.. currentmodule:: graphql.type |
| 5 |
|
| 6 |
Above we defined the GraphQL schema as Python code, using the :class:`GraphQLSchema` |
| 7 |
class and other classes representing the various GraphQL types. |
| 8 |
|
| 9 |
GraphQL-core 3 also provides a language-agnostic way of defining a GraphQL schema |
| 10 |
using the GraphQL schema definition language (SDL) which is also part of the GraphQL |
| 11 |
specification. To do this, we simply feed the SDL as a string to the |
| 12 |
:func:`~graphql.utilities.build_schema` function in :mod:`graphql.utilities`:: |
| 13 |
|
| 14 |
from graphql import build_schema |
| 15 |
|
| 16 |
schema = build_schema(""" |
| 17 |
|
| 18 |
enum Episode { NEWHOPE, EMPIRE, JEDI } |
| 19 |
|
| 20 |
interface Character { |
| 21 |
id: String! |
| 22 |
name: String |
| 23 |
friends: [Character] |
| 24 |
appearsIn: [Episode] |
| 25 |
} |
| 26 |
|
| 27 |
type Human implements Character { |
| 28 |
id: String! |
| 29 |
name: String |
| 30 |
friends: [Character] |
| 31 |
appearsIn: [Episode] |
| 32 |
homePlanet: String |
| 33 |
} |
| 34 |
|
| 35 |
type Droid implements Character { |
| 36 |
id: String! |
| 37 |
name: String |
| 38 |
friends: [Character] |
| 39 |
appearsIn: [Episode] |
| 40 |
primaryFunction: String |
| 41 |
} |
| 42 |
|
| 43 |
type Query { |
| 44 |
hero(episode: Episode): Character |
| 45 |
human(id: String!): Human |
| 46 |
droid(id: String!): Droid |
| 47 |
} |
| 48 |
""") |
| 49 |
|
| 50 |
The result is a :class:`GraphQLSchema` object just like the one we defined above, except |
| 51 |
for the resolver functions which cannot be defined in the SDL. |
| 52 |
|
| 53 |
We would need to manually attach these functions to the schema, like so:: |
| 54 |
|
| 55 |
schema.query_type.fields['hero'].resolve = get_hero |
| 56 |
schema.get_type('Character').resolve_type = get_character_type |
| 57 |
|
| 58 |
Another problem is that the SDL does not define the server side values of the |
| 59 |
``Episode`` enum type which are returned by the resolver functions and which are |
| 60 |
different from the names used for the episode. |
| 61 |
|
| 62 |
So we would also need to manually define these values, like so:: |
| 63 |
|
| 64 |
for name, value in schema.get_type('Episode').values.items(): |
| 65 |
value.value = EpisodeEnum[name].value |
| 66 |
|
| 67 |
This would allow us to query the schema built from SDL just like the manually assembled |
| 68 |
schema:: |
| 69 |
|
| 70 |
from graphql import graphql_sync |
| 71 |
|
| 72 |
result = graphql_sync(schema, """ |
| 73 |
{ |
| 74 |
hero(episode: EMPIRE) { |
| 75 |
name |
| 76 |
appearsIn |
| 77 |
} |
| 78 |
} |
| 79 |
""") |
| 80 |
print(result) |
| 81 |
|
| 82 |
And we would get the expected result:: |
| 83 |
|
| 84 |
ExecutionResult( |
| 85 |
data={'hero': {'name': 'Luke Skywalker', |
| 86 |
'appearsIn': ['NEWHOPE', 'EMPIRE', 'JEDI']}}, |
| 87 |
errors=None) |