3

I'm trying to use python to parse a graphql query, alter it, and turn it back into a string query that I can pass to the graphql server.

Specifically, I'm trying to ensure that a query will always have the pageInfo paging information, so if I'm executing a query, I will always be able to automatically page through the results, even if a user might forget that stanza in their actual query.

It seems surprisingly difficult to parse a graphql query into something useful, and then be able to go from the parsed data representation back to the query string. Is there a library that google isn't able to turn up for me?

Thanks so much for any help!

2 Answers 2

3

The core library includes a parse function for parsing strings into AST and a print_ast function for converting the AST back to a string.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi Daniel, thanks! I somehow overlooked print_ast - you don't happen to have any examples of how to edit this ast, do you? Much obliged!
1

I've just faced a similar problem. For future reference: the way you edit the AST is by creating a visitor class that will enter the tree and modify it to your liking. It's described in the documentation here. For example, in order to remove field named attributes I used following code:

from graphql import parse, print_ast
from graphql.language.visitor import visit, Visitor, REMOVE, IDLE

class RemoveAttributesVisitor(Visitor):
    def enter_field(self, node, key, parent, path, ancestors):
        if node.name.value == "attributes":
            return REMOVE
        return IDLE

ast = parse(PRODUCT_QUERY)
new_ast = visit(ast, RemoveAttributesVisitor())
updated_query = print_ast(new_ast)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.