| 1 |
Extending a Schema |
| 2 |
------------------ |
| 3 |
|
| 4 |
.. currentmodule:: graphql.utilities |
| 5 |
|
| 6 |
With GraphQL-core 3 you can also extend a given schema using type extensions. For |
| 7 |
example, we might want to add a ``lastName`` property to our ``Human`` data type to |
| 8 |
retrieve only the last name of the person. |
| 9 |
|
| 10 |
This can be achieved with the :func:`extend_schema` function as follows:: |
| 11 |
|
| 12 |
from graphql import extend_schema, parse |
| 13 |
|
| 14 |
schema = extend_schema(schema, parse(""" |
| 15 |
extend type Human { |
| 16 |
lastName: String |
| 17 |
} |
| 18 |
""")) |
| 19 |
|
| 20 |
Note that this function expects the extensions as an AST, which we can get using the |
| 21 |
:func:`~graphql.language.parse` function. Also note that the :func:`extend_schema` |
| 22 |
function does not alter the original schema, but returns a new schema object. |
| 23 |
|
| 24 |
We also need to attach a resolver function to the new field:: |
| 25 |
|
| 26 |
def get_last_name(human, info): |
| 27 |
return human['name'].rsplit(None, 1)[-1] |
| 28 |
|
| 29 |
schema.get_type('Human').fields['lastName'].resolve = get_last_name |
| 30 |
|
| 31 |
Now we can query only the last name of a human:: |
| 32 |
|
| 33 |
from graphql import graphql_sync |
| 34 |
|
| 35 |
result = graphql_sync(schema, """ |
| 36 |
{ |
| 37 |
human(id: "1000") { |
| 38 |
lastName |
| 39 |
homePlanet |
| 40 |
} |
| 41 |
} |
| 42 |
""") |
| 43 |
print(result) |
| 44 |
|
| 45 |
This query will give the following result:: |
| 46 |
|
| 47 |
ExecutionResult( |
| 48 |
data={'human': {'lastName': 'Skywalker', 'homePlanet': 'Tatooine'}}, |
| 49 |
errors=None) |
| 50 |
|