graphql / graphql.github.io

GraphQL Documentation at graphql.org

Home Page:https://graphql.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Adding a tool for python to `/code`

denisart opened this issue · comments

Description

Hello, thank for your project. I use https://graphql.org/ in my work often.

I want to offer a useful tool for a python GraphQL client: graphql-query. It is a tool for complete GraphQL query string generation for python.

docs: https://denisart.github.io/graphql-query/
src: https://github.com/denisart/graphql-query
pypi: https://pypi.org/project/graphql-query/

Motivation

Managing GraphQL queries in python as strings is tricky. A popular discussion: best-way-to-construct-a-graphql-query-string-in-python.

With graphql_query it is easy.

Example

An example from documetation:

For generation of the following query

query Hero($episode: Episode, $withFriends: Boolean!) {
  hero(episode: $episode) {
    name
    friends @include(if: $withFriends) {
      name
    }
  }
}

we have

from graphql_query import Argument, Directive, Field, Operation, Query, Variable

var_episode = Variable(name="episode", type="Episode")
var_withFriends = Variable(name="withFriends", type="Boolean!")

arg_episode = Argument(name="episode", value=var_episode)
arg_if = Argument(name="if", value=var_withFriends)

directive_include = Directive(name="include", arguments=[arg_if])

hero = Query(
    name="hero",
    arguments=[arg_episode],
    fields=[
        "name",
        Field(name="friends", fields=["name"], directives=[directive_include])
    ]
)
operation = Operation(
    type="query", name="Hero", variables=[var_episode, var_withFriends], queries=[hero]
)
print(operation.render())
"""
query Hero(
  $episode: Episode
  $withFriends: Boolean!
) {
  hero(
    episode: $episode
  ) {
    name
    friends @include(
      if: $withFriends
    ) {
      name
    }
  }
}
"""

We can sharing created GraphQL types to other operations easy.

Other examples

All examples from graphql.org documentation can be found at https://denisart.github.io/graphql-query/usage.html

Collaboration

I can add this package to the section code/python/tools or to tools/general. This should improve the use of python as a GraphQL client.

Additional Context