GraphQL Query DSL for Python

1.4.0 · active · verified Thu Apr 16

graphql-query is a Python library that provides a complete Domain Specific Language (DSL) for constructing GraphQL queries programmatically. It allows developers to build complex GraphQL queries, mutations, and fragments using Python objects, simplifying the process of generating valid GraphQL syntax. The library is actively maintained with regular updates, currently at version 1.4.0.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to construct basic GraphQL queries using the `Query`, `Field`, and `Argument` classes. The `render()` method converts the Python object structure into a valid GraphQL query string.

from graphql_query import Query, Field, Argument

# Example 1: Simple Query
simple_query = Query(
    name="myQuery",
    fields=[
        Field(name="hero", fields=[Field(name="name")]),
    ]
)
print(f"Simple Query: {simple_query.render()}")
# Expected output: { myQuery { hero { name } } }

# Example 2: Query with Arguments
query_with_args = Query(
    name="character",
    arguments=[
        Argument(name="id", value="1000")
    ],
    fields=[
        Field(name="name"),
        Field(name="appearsIn")
    ]
)
print(f"Query with Arguments: {query_with_args.render()}")
# Expected output: query character($id: String = "1000") { character(id: $id) { name appearsIn } }

view raw JSON →