Skip to content

GraphQL API Documentation


GraphQL Types — Examples


zmag.Type(**kwargs)

GraphQL Type base class.

Example:

class Author(zmag.Type):
    first_name: str
    last_name: str

    @property
    async def full_name(self) -> str:
        return f"{self.first_name} {self.last_name}"

zmag.Model(_id=None, id=None) dataclass

GraphQL Model type with a private _id field and a public id field included.

Example:

class Author(zmag.Type):
    @property
    async def merged_ids(self) -> str:
        return f"{self._id} and {self.id}"

zmag.BaseType(**kwargs)

GraphQL Abstract Type for defining common fields and creating a base class for other types.

Example:

# Abstract Class
class MyBase(zmag.BaseType):
    shared_field: str

    class Meta:
        abstract = True

# New Type - Inheritor
class MyType(MyBase): ...

GraphQL Inputs — Examples


zmag.Input

Base class for GraphQL Input types, must be used with zmag.input function.

Example:

input = zmag.input()

@input
class Form(zmag.Input):
    name: str
    ...

input: Form instance-attribute

Returns the processed value from zmag.Input.

Example:

async def mutation(form: Form):
    print(form.input)

zmag.Form(data=SimpleNamespace(), errors=list(), is_valid=False, next=None) dataclass

Represents an Input response.

This class extends zmag.Input and provides methods to handle form data, including cleaning and converting it to a dictionary format.

Attributes:

  • data (Any) –

    The input data stored in a SimpleNamespace.

  • errors (list) –

    A list of errors associated with the form.

  • is_valid (bool) –

    Indicates whether the form data is valid.

Example:

class Form(zmag.Input): ...

async def mutation(form: Form):
    print(form.input)
    print(form.input.clean())
    print(form.input.dict(True))

dict(clean=False)

Convert the form data to a dict.

Parameters:

  • clean (bool, default: False ) –

    If True, exclude keys with UNSET values from the dictionary.

Returns:

  • data ( dict ) –

    The input data as a dictionary, optionally cleaned of UNSET values.

clean()

Convert the form data to a SimpleNamespace, excluding UNSET values.

Returns:

  • data ( SimpleNamespace ) –

    The input data as a SimpleNamespace, cleaned of UNSET values.


zmag.input(prefix=None, suffix=None)

Creates a decorator for Inputs, optionally adding a common prefix or suffix.

This function extends zmag.Input.

Parameters:

  • prefix (str | list[str] | None, default: None ) –

    The prefix to be added to each field in the class.

  • suffix (str | list[str] | None, default: None ) –

    The suffix to be added to each field in the class.

Returns:

  • decorator ( Callable ) –

    To wrap GraphQL Input types.

Example:

Author = zmag.input("Author")

@Author
class Create(zmag.Input): ... # AuthorCreate

@Author
class Update(zmag.Input): ... # AuthorUpdate

zmag.value(default=UNSET, required=False, regex=None, rules=None, clean=None, deprecation_reason=None)

Configuration options for the Input value.

This function extends zmag.Input.

Parameters:

  • default (Any, default: UNSET ) –

    The default value for the field.

  • required (bool, default: False ) –

    Indicates whether the field is mandatory.

  • regex (dict | None, default: None ) –

    A dictionary defining regular expressions for field validation.

  • rules (list | None, default: None ) –

    A list of validation rules to apply to the field.

  • clean (ValueCleaner | None, default: None ) –

    A callable used to configure preprocess of the value.

  • deprecation_reason (str | None, default: None ) –

    A message explaining why the field is deprecated.

Example:

GraphQL: (form: {x: "required_field", email: "demo@helloworld.com"})

class MyForm(zmag.Input):
    # A required field with no default value,
    # ensuring the field must be filled.
    x: str = zmag.value(required=True)

    # A field with a default value,
    # optionally using a function for initialization.
    y: str = zmag.value(default="Some Value")
    y: str = zmag.value(default=lambda: "Some Value")

    # A deprecated field "not for use",
    # in the near future or at all.
    z: str = zmag.value(deprecation_reason="Value is deprecated")

    # A complex field setup demonstrating validation,
    # cleaning, and transformation of input data.
    email: str = zmag.value(
        regex={
            # A field with regex validation.
            r"[\w\.-]+@[\w\.-]+": "Invalid email address"
        },
        rules=[
            # Additional custom validation rules.
            (lambda v: v.startswith("demo") or "Invalid input")
        ],
        clean=zmag.clean(
            regex=[
                # Replace using regex in the cleaning phase.
                (r"^hello", "hola"),
                (r"com", "api"),
            ],
            rules=[
                # Apply custom rules after regex replacements.
                (lambda v: v.upper())
            ],
        ),
    )

zmag.clean(regex=None, rules=None)

Creates a ValueCleaner configuration with regex filters and custom rules.

This function extends zmag.value.

Parameters:

  • regex (list | None, default: None ) –

    A list of regex patterns for filtering input value.

  • rules (list | None, default: None ) –

    A list of rules (functions or lambdas) to apply to input value.

Returns:

  • config ( ValueCleaner ) –

    A dictionary containing regex and rules for input value cleaning.

Example:

zmag.clean(
    regex=[
        # Replace text using regex in the cleaning phase.
        (r"^hello", "hola"),
        (r"com", "api"),
    ],
    rules=[
        # Apply further custom rules after regex replacements.
        (lambda v: v.upper())
    ],
)

GraphQL Operations — Examples


zmag.gql(cls=None)

This class decorator transforms a Python class into GraphQL operations.

When applied to a class, @zmag.gql interprets inner classes named Query and Mutation as containers for GraphQL query and mutation methods, respectively. These methods can then be invoked as part of a GraphQL API.

Attributes:

  • Meta (class) –

    Defines metadata for the GraphQL class, such as the associated app and model.

  • Query (class) –

    Contains methods that represent GraphQL queries. Each method should be an async function and can return various data types.

  • Mutation (class) –

    Contains methods that represent GraphQL mutations. Each method should be an async function and can accept input data for modifying server-side state.

Meta class Attributes:
  • app (str | bool | None): Specifies a prefix for the GraphQL field names. If set to None, the prefix is omitted, and the field names are based directly on the method names.

  • model (str | type | None): When specified, prefixes the GraphQL field names with the model name. This helps in creating more descriptive and structured GraphQL schemas.

Tip

This decorator allows you to seamlessly integrate Python classes with a GraphQL API.

Example:

@zmag.gql
class Graphql:

    class Meta:
        app = True
        model = "Book"

    class Query: ...

    class Mutation: ...

GraphQL Output — Examples


zmag.Edge: TypeAlias = Connection[T, JSON] module-attribute


zmag.edge(edges=None, count=0, pages=0, has_next=False, has_previous=False, computed=None)

Extends Edges used to return a Page response.

Example:

async def search(self) -> zmag.Edge[types.Book]:
    return zmag.edge(
        count=1,
        pages=1,
        edges=[
            types.Book(
                id=1,
                title="The Great Gatsby",
            ),
        ],
        computed={
            "someComputedValue": 100,
        },
    )

zmag.Mutation(item=None, many=field(default_factory=list), error=None, deleted=0) dataclass

Represents a GraphQL Mutation response, handling the outcome of mutation operations.

Example:

async def create(self) -> zmag.Mutation[types.Book]:
    data = form.input.dict(True)
    return zmag.Mutation(
        item=types.Book(title=data.get("title")),
    )

zmag.Error(field=None, type=None, text=None) dataclass

A structured format for GraphQL error messages to be used in Errors responses.


zmag.Errors(messages=field(default_factory=list), meta=field(default_factory=dict), error=True) dataclass

A comprehensive response object for handling multiple GraphQL Errors.

Example:

Errors(
    meta={"note": "reset form."}
    messages=[
        Error(field="username", type="invalid", text="username must be lowercase."),
    ],
)

zmag.input_error(messages, meta=None)

A simplified error handler for mutation Errors.

Returns:

  • response ( Mutation ) –

    GraphQL Mutation

async def create(self, form: inputs.Create) -> zmag.Mutation[types.Book]:
    # Not Valid
    if not form.input.is_valid:
        return zmag.input_error(form.input.errors)

    # Is Valid
    ...

GraphQL Input — Examples


zmag.Pagination

An input for managing pagination, for efficient navigation and retrieval of database records.

Example:

class Query:
    async def search(self, pagination: zmag.Pagination):
        ...

zmag.Selector

A utility for selecting database record(s).

Example:

class Query:
    async def detail(self, record: zmag.Selector):
        ...