Modify query programmatically
See original GitHub issueSent here from https://github.com/graphql-python/gql/issues/272
There is a way in gql to construct queries programmatically with DSL module or by parsing a string into AST with gql.gql() and then using print_ast from graphql to get back the string.
import gql
dg = gql.gql("""
query getContinents {
continents {
code
name
}
}
""")
from graphql import print_ast
print(print_ast(dg))
What is not clear is how to actually find nodes in AST and edit or expand them. For example, finding a parent of node in the query below (continents) and adding an attribute to it ((code:"AF")).
query getContinents {
continents {
code
name
}
}
So that the query becomes.
query getContinents {
continents (code:"AF") {
code
name
}
}
I looked into the docs, but it doesn’t actually explain.
- How to find AST node that needs modification?
- How to modify it (upsert attributes)?
The documentation container chapter about schemas https://graphql-core-3.readthedocs.io/en/latest/usage/extension.html?highlight=modify ast#extending-a-schema and as I am new to GraphQL I am not yet sure if schema and query are the same things.
Feature requests
I am not sure GraphQL.js includes this too and not sure that fundamentally changes the way GraphQL works.
Issue Analytics
- State:
- Created 2 years ago
- Comments:7 (4 by maintainers)

Top Related StackOverflow Question
@abitrolly I’m currently going through the old tickets before creating the next release. Feel free to reopen or open a new issue if you have concrete questions.
@abitrolly You can use a Visitor to traverse the AST. This will also give you access to the immediate parent and full list of ancestors of the current node.
Here is an example of a visitor that searches for a field node with the name ‘code’, and then adds another field node with the name ‘newField’ to its parent.
Note: It is recommended to use a FrozenList instead of an ordinary list to make the nodes hashable.