graphql-typed-python 0.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ """Build named operations with the types in your generated schema module."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Literal
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class Variable:
9
+ name: str
10
+
11
+
12
+ def var(name: str) -> Variable:
13
+ return Variable(name)
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class Operation:
18
+ kind: Literal["query", "mutation"]
19
+ name: str
20
+ select: object
graphql_typed/cli.py ADDED
@@ -0,0 +1,42 @@
1
+ import argparse
2
+ from pathlib import Path
3
+
4
+ from graphql import GraphQLError
5
+
6
+ from graphql_typed.generator import generate
7
+
8
+
9
+ def main() -> None:
10
+ parser = argparse.ArgumentParser(prog="graphql-typed")
11
+ commands = parser.add_subparsers(dest="command", required=True)
12
+ command = commands.add_parser(
13
+ "generate", help="Generate schema types and typed operation clients"
14
+ )
15
+ command.add_argument(
16
+ "source", help="SDL file, introspection JSON file, or endpoint URL"
17
+ )
18
+ command.add_argument(
19
+ "--out", type=Path, required=True, help="Generated package directory"
20
+ )
21
+ command.add_argument(
22
+ "--operations", metavar="MODULE:FUNCTION", help="Named operation factory"
23
+ )
24
+ command.add_argument(
25
+ "--no-ssl",
26
+ action="store_true",
27
+ help="Disable TLS verification for schema fetching",
28
+ )
29
+ args = parser.parse_args()
30
+ try:
31
+ generate(
32
+ args.source,
33
+ args.out,
34
+ operations=args.operations,
35
+ verify_ssl=not args.no_ssl,
36
+ )
37
+ except (OSError, TypeError, ValueError, GraphQLError) as error:
38
+ parser.exit(1, f"{error}\n")
39
+
40
+
41
+ if __name__ == "__main__":
42
+ main()
@@ -0,0 +1 @@
1
+ from .api import generate as generate
@@ -0,0 +1,65 @@
1
+ import keyword
2
+ import os
3
+ import shutil
4
+ import subprocess
5
+ import sys
6
+ from pathlib import Path
7
+ from tempfile import TemporaryDirectory
8
+
9
+ from graphql import print_schema
10
+
11
+ from graphql_typed.generator.loader import load_schema
12
+ from graphql_typed.generator.types import render_schema
13
+ from graphql_typed.generator.write import publish
14
+
15
+
16
+ def generate(
17
+ source: str | Path,
18
+ out: str | Path,
19
+ *,
20
+ operations: str | None = None,
21
+ verify_ssl: bool = True,
22
+ ) -> None:
23
+ """Generate a schema module and, when supplied a factory, its typed clients."""
24
+ output = Path(out).resolve()
25
+ if not output.name.isidentifier() or keyword.iskeyword(output.name):
26
+ raise ValueError(f"Output directory must name a Python package: {output}")
27
+ schema = load_schema(str(source), verify_ssl=verify_ssl)
28
+ output.parent.mkdir(parents=True, exist_ok=True)
29
+ with TemporaryDirectory(dir=output.parent) as temporary:
30
+ stage = Path(temporary) / output.name
31
+ stage.mkdir()
32
+ (stage / "__init__.py").touch()
33
+ (stage / "py.typed").touch()
34
+ (stage / "schema.py").write_text(render_schema(schema), encoding="utf-8")
35
+ if operations is not None:
36
+ root = output.parent
37
+ while (root / "__init__.py").is_file():
38
+ root = root.parent
39
+ package = ".".join(output.relative_to(root).parts)
40
+ (stage.parent / "source.graphql").write_text(
41
+ print_schema(schema), encoding="utf-8"
42
+ )
43
+ env = {**os.environ, "PYTHONPATH": os.pathsep.join([str(root), *sys.path])}
44
+ run = subprocess.run(
45
+ [
46
+ sys.executable,
47
+ "-m",
48
+ "graphql_typed.generator.factory",
49
+ str(stage),
50
+ package,
51
+ operations,
52
+ ],
53
+ check=False,
54
+ env=env,
55
+ text=True,
56
+ stderr=subprocess.PIPE,
57
+ )
58
+ if run.returncode:
59
+ raise ValueError(f"Operation generation failed:\n{run.stderr.strip()}")
60
+ shutil.copyfile(
61
+ Path(__file__).parents[1] / "templates/transport.py",
62
+ stage / "transport.py",
63
+ )
64
+
65
+ publish(stage, output)
@@ -0,0 +1,131 @@
1
+ from collections import defaultdict
2
+ from collections.abc import Iterable
3
+
4
+ from graphql import (
5
+ FieldNode,
6
+ GraphQLNonNull,
7
+ GraphQLObjectType,
8
+ GraphQLSchema,
9
+ SelectionNode,
10
+ get_named_type,
11
+ )
12
+
13
+ from graphql_typed import Operation
14
+ from graphql_typed.generator.operations import Document
15
+ from graphql_typed.generator.types import Inputs, Names, annotation, dictionary, scalar
16
+
17
+
18
+ def response(
19
+ name: str,
20
+ parent: GraphQLObjectType,
21
+ selections: Iterable[SelectionNode],
22
+ names: Names,
23
+ definitions: list[str],
24
+ ) -> None:
25
+ groups: dict[str, list[FieldNode]] = defaultdict(list)
26
+ for field in selections:
27
+ assert isinstance(field, FieldNode)
28
+ groups[(field.alias or field.name).value].append(field)
29
+ items = []
30
+ for key, nodes in groups.items():
31
+ field_name = nodes[0].name.value
32
+ if field_name == "__typename":
33
+ item_type = f"t.Literal[{parent.name!r}]"
34
+ else:
35
+ field_type = parent.fields[field_name].type
36
+ target = get_named_type(field_type)
37
+ if isinstance(target, GraphQLObjectType):
38
+ nested = names.take(f"{name}_{key}")
39
+ response(
40
+ nested,
41
+ target,
42
+ (
43
+ child
44
+ for node in nodes
45
+ if node.selection_set
46
+ for child in node.selection_set.selections
47
+ ),
48
+ names,
49
+ definitions,
50
+ )
51
+ item_type = annotation(field_type, nested)
52
+ else:
53
+ item_type = annotation(field_type, scalar(target, input_=False))
54
+ items.append((key, item_type, True))
55
+ definitions.append(dictionary(name, items))
56
+
57
+
58
+ def render_client(
59
+ schema: GraphQLSchema, operations: Iterable[Operation]
60
+ ) -> tuple[str, str]:
61
+ names = Names()
62
+ inputs = Inputs(schema, names, authoring=False)
63
+ types = ["import typing as t", *inputs.definitions]
64
+ client = [
65
+ (
66
+ "from __future__ import annotations\nimport typing as t\n"
67
+ "from . import types\nfrom .transport import AsyncExecutor, SyncExecutor"
68
+ )
69
+ ]
70
+ documents: dict[str, dict[str, str]] = {"query": {}, "mutation": {}}
71
+ seen: set[str] = set()
72
+ for op in operations:
73
+ if not isinstance(op, Operation):
74
+ raise TypeError("Operation factory must return an iterable of operations")
75
+ if op.name in seen:
76
+ raise ValueError(f"Duplicate operation name {op.name!r}")
77
+ seen.add(op.name)
78
+ doc = Document(schema, op)
79
+ documents[op.kind][op.name] = doc.text
80
+ data = names.take(op.name + "Data")
81
+ assert doc.root is not None
82
+ response(data, doc.root, doc.fields, names, types)
83
+ params = ""
84
+ if doc.variables:
85
+ variables = names.take(op.name + "Variables")
86
+ fields = [
87
+ (k, inputs.type(v), isinstance(v, GraphQLNonNull))
88
+ for k, v in doc.variables.items()
89
+ ]
90
+ types.append(dictionary(variables, fields))
91
+ default = "" if any(required for _, _, required in fields) else " = ..."
92
+ params = f", *, variables: types.{variables}{default}"
93
+ for prefix, modifier in [("Sync", ""), ("Async", "async ")]:
94
+ client.append(
95
+ f"class {prefix}_{op.name}(t.Protocol):\n"
96
+ f" {modifier}def __call__(self{params}) -> types.{data}: ..."
97
+ )
98
+
99
+ for kind, docs in documents.items():
100
+ if docs:
101
+ entries = "\n".join(f" {key!r}: {text!r}," for key, text in docs.items())
102
+ client.append(f"_{kind}: dict[str, str] = {{\n{entries}\n}}")
103
+ for prefix, class_name in [("Sync", "Client"), ("Async", "AsyncClient")]:
104
+ methods = []
105
+ for kind, docs in documents.items():
106
+ if not docs:
107
+ continue
108
+ bind = f"self._bind(name, _{kind})"
109
+ for name in docs:
110
+ protocol = f"{prefix}_{name}"
111
+ signature = (
112
+ f" def {kind}(self, name: t.Literal[{name!r}]) -> {protocol}:"
113
+ )
114
+ if len(docs) == 1:
115
+ methods.extend(
116
+ [signature, f" return t.cast({protocol}, {bind})"]
117
+ )
118
+ else:
119
+ methods.extend([" @t.overload", signature + " ..."])
120
+ if len(docs) > 1:
121
+ methods.extend(
122
+ [
123
+ f" def {kind}(self, name: str) -> t.Any:",
124
+ f" return {bind}",
125
+ ]
126
+ )
127
+ client.append(
128
+ f"class {class_name}({prefix}Executor):\n"
129
+ + ("\n".join(methods) or " pass")
130
+ )
131
+ return "\n\n".join(types) + "\n", "\n\n".join(client) + "\n"
@@ -0,0 +1,41 @@
1
+ """Evaluate the user's factory against the freshly staged schema in a fresh interpreter."""
2
+
3
+ import importlib
4
+ import importlib.util
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from graphql import build_schema
9
+
10
+ from graphql_typed.generator.client import render_client
11
+
12
+
13
+ def compile_factory(stage: Path, package: str, factory: str) -> None:
14
+ module, sep, function = factory.partition(":")
15
+ if not sep or not module or not function:
16
+ raise ValueError("Expected --operations module:function")
17
+
18
+ # A finder also handles nested output packages and imports made by shared helpers.
19
+ class StagedPackage:
20
+ @staticmethod
21
+ def find_spec(fullname: str, path=None, target=None):
22
+ if fullname == package:
23
+ return importlib.util.spec_from_file_location(
24
+ package,
25
+ stage / "__init__.py",
26
+ submodule_search_locations=[str(stage)],
27
+ )
28
+
29
+ sys.meta_path.insert(0, StagedPackage())
30
+ # Re-read user modules even after a same-size edit within one timestamp tick.
31
+ sys.pycache_prefix = str(stage.parent / "cache")
32
+ sys.dont_write_bytecode = True
33
+ operations = getattr(importlib.import_module(module), function)()
34
+ schema = build_schema((stage.parent / "source.graphql").read_text(encoding="utf-8"))
35
+ types, client = render_client(schema, operations)
36
+ (stage / "types.py").write_text(types, encoding="utf-8")
37
+ (stage / "client.py").write_text(client, encoding="utf-8")
38
+
39
+
40
+ if __name__ == "__main__":
41
+ compile_factory(Path(sys.argv[1]), sys.argv[2], sys.argv[3])
@@ -0,0 +1,39 @@
1
+ import json
2
+ import ssl
3
+ from pathlib import Path
4
+ from urllib.request import Request, urlopen
5
+
6
+ from graphql import (
7
+ GraphQLSchema,
8
+ assert_valid_schema,
9
+ build_client_schema,
10
+ build_schema,
11
+ get_introspection_query,
12
+ )
13
+
14
+
15
+ def load_schema(source: str, *, verify_ssl: bool = True) -> GraphQLSchema:
16
+ if source.startswith(("http://", "https://")):
17
+ request = Request(
18
+ source,
19
+ data=json.dumps({"query": get_introspection_query()}).encode(),
20
+ headers={"Content-Type": "application/json", "Accept": "application/json"},
21
+ )
22
+ context = None if verify_ssl else ssl._create_unverified_context()
23
+ with urlopen(request, timeout=30, context=context) as response:
24
+ document = json.load(response)
25
+ else:
26
+ path = Path(source)
27
+ content = path.read_text(encoding="utf-8")
28
+ if path.suffix.lower() != ".json" and not content.lstrip().startswith("{"):
29
+ schema = build_schema(content)
30
+ assert_valid_schema(schema)
31
+ return schema
32
+ document = json.loads(content)
33
+ if not isinstance(document, dict):
34
+ raise TypeError("Expected an introspection JSON object")
35
+ if document.get("errors"):
36
+ raise ValueError(f"Schema introspection failed: {document['errors']}")
37
+ schema = build_client_schema(document.get("data", document))
38
+ assert_valid_schema(schema)
39
+ return schema
@@ -0,0 +1,148 @@
1
+ """Compile a selection dictionary into a validated, named GraphQL document."""
2
+
3
+ import json
4
+ from typing import Any
5
+
6
+ from graphql import (
7
+ GraphQLEnumType,
8
+ GraphQLInputObjectType,
9
+ GraphQLList,
10
+ GraphQLNonNull,
11
+ GraphQLObjectType,
12
+ GraphQLSchema,
13
+ GraphQLType,
14
+ OperationDefinitionNode,
15
+ assert_name,
16
+ get_named_type,
17
+ is_leaf_type,
18
+ parse,
19
+ print_ast,
20
+ validate,
21
+ )
22
+
23
+ from graphql_typed import Operation, Variable
24
+
25
+
26
+ def object_value(value: object, path: str) -> dict[str, Any]:
27
+ if not isinstance(value, dict) or not all(isinstance(k, str) for k in value):
28
+ raise ValueError(f"{path}: expected a dictionary with string keys")
29
+ return value
30
+
31
+
32
+ def literal(value: Any) -> str:
33
+ if isinstance(value, Variable):
34
+ raise TypeError(
35
+ f"Cannot infer the type of ${value.name} inside a scalar literal"
36
+ )
37
+ if isinstance(value, dict):
38
+ fields = (f"{assert_name(key)}: {literal(item)}" for key, item in value.items())
39
+ return "{" + ", ".join(fields) + "}"
40
+ if isinstance(value, list):
41
+ return "[" + ", ".join(literal(item) for item in value) + "]"
42
+ return json.dumps(value, allow_nan=False)
43
+
44
+
45
+ class Document:
46
+ def __init__(self, schema: GraphQLSchema, op: Operation):
47
+ assert_name(op.name)
48
+ self.variables: dict[str, GraphQLType] = {}
49
+ self.locations: dict[str, str] = {}
50
+ self.root = {"query": schema.query_type, "mutation": schema.mutation_type}[
51
+ op.kind
52
+ ]
53
+ if self.root is None:
54
+ raise ValueError(f"Schema has no {op.kind} root")
55
+ body = self.selection(self.root, op.select)
56
+ declarations = ", ".join(f"${k}: {t}" for k, t in self.variables.items())
57
+ signature = f"({declarations})" if declarations else ""
58
+ ast = parse(f"{op.kind} {op.name}{signature} {body}")
59
+ errors = validate(schema, ast)
60
+ if errors:
61
+ raise ValueError(
62
+ "\n".join(f"{op.name}: {error.message}" for error in errors)
63
+ )
64
+ self.text = print_ast(ast)
65
+ definition = ast.definitions[0]
66
+ assert isinstance(definition, OperationDefinitionNode)
67
+ self.fields = definition.selection_set.selections
68
+
69
+ def value(self, value: Any, type_: GraphQLType, path: str) -> str:
70
+ if isinstance(value, Variable):
71
+ name = assert_name(value.name)
72
+ previous = self.variables.setdefault(name, type_)
73
+ location = self.locations.setdefault(name, path)
74
+ if str(previous) != str(type_):
75
+ raise ValueError(
76
+ f"${name}: {location} expects {previous}, {path} expects {type_}"
77
+ )
78
+ return f"${name}"
79
+ inner = type_.of_type if isinstance(type_, GraphQLNonNull) else type_
80
+ if value is None:
81
+ return "null"
82
+ if isinstance(inner, GraphQLList):
83
+ if isinstance(value, list):
84
+ return (
85
+ "["
86
+ + ", ".join(
87
+ self.value(v, inner.of_type, path + "[]") for v in value
88
+ )
89
+ + "]"
90
+ )
91
+ return self.value(value, inner.of_type, path + "[]")
92
+ if isinstance(inner, GraphQLInputObjectType):
93
+ items = []
94
+ for key, v in object_value(value, path).items():
95
+ field = inner.fields.get(key)
96
+ if field is None:
97
+ raise ValueError(f"{path}: unknown input field {key!r}")
98
+ items.append(f"{key}: {self.value(v, field.type, f'{path}.{key}')}")
99
+ return "{" + ", ".join(items) + "}"
100
+ if isinstance(inner, GraphQLEnumType):
101
+ return assert_name(value)
102
+ return literal(value)
103
+
104
+ def selection(self, parent: GraphQLObjectType, value: object) -> str:
105
+ parts = []
106
+ for key, selections in object_value(value, parent.name).items():
107
+ if selections == []:
108
+ raise ValueError(f"{parent.name}.{key}: empty selection list")
109
+ for item in selections if isinstance(selections, list) else [selections]:
110
+ options = (
111
+ {} if item is True else object_value(item, f"{parent.name}.{key}")
112
+ )
113
+ parts.append(self.field(parent, key, options))
114
+ if not parts:
115
+ raise ValueError(f"{parent.name}: select at least one field")
116
+ return "{ " + " ".join(parts) + " }"
117
+
118
+ def field(
119
+ self, parent: GraphQLObjectType, key: str, options: dict[str, Any]
120
+ ) -> str:
121
+ path = f"{parent.name}.{key}"
122
+ if extra := options.keys() - {"alias", "args", "select"}:
123
+ raise ValueError(f"{path}: unknown selection options {sorted(extra)}")
124
+ prefix = f"{assert_name(options['alias'])}: " if "alias" in options else ""
125
+ if key == "__typename" and options.keys() <= {"alias"}:
126
+ return prefix + key
127
+ field = parent.fields.get(key)
128
+ if field is None:
129
+ raise ValueError(f"Unknown field {path}")
130
+ args = []
131
+ for name, value in object_value(options.get("args", {}), path).items():
132
+ arg = field.args.get(name)
133
+ if arg is None:
134
+ raise ValueError(f"{path}: unknown argument {name!r}")
135
+ args.append(f"{name}: {self.value(value, arg.type, f'{path}({name})')}")
136
+ call = "(" + ", ".join(args) + ")" if args else ""
137
+ target = get_named_type(field.type)
138
+ if isinstance(target, GraphQLObjectType):
139
+ child = " " + self.selection(target, options.get("select"))
140
+ elif is_leaf_type(target):
141
+ if "select" in options:
142
+ raise ValueError(f"{path}: a leaf field cannot have a selection")
143
+ child = ""
144
+ else:
145
+ raise ValueError(
146
+ f"{path}: abstract result type {target.name} is unsupported"
147
+ )
148
+ return prefix + key + call + child
@@ -0,0 +1,159 @@
1
+ """Shared rendering of schema inputs, selection dictionaries and response fields."""
2
+
3
+ from collections.abc import Iterable, Mapping
4
+
5
+ from graphql import (
6
+ GraphQLArgument,
7
+ GraphQLEnumType,
8
+ GraphQLInputField,
9
+ GraphQLInputObjectType,
10
+ GraphQLList,
11
+ GraphQLNamedType,
12
+ GraphQLNonNull,
13
+ GraphQLObjectType,
14
+ GraphQLSchema,
15
+ GraphQLType,
16
+ Undefined,
17
+ get_named_type,
18
+ is_abstract_type,
19
+ )
20
+
21
+
22
+ class Names:
23
+ def __init__(self) -> None:
24
+ self.used: set[str] = set()
25
+
26
+ def take(self, base: str) -> str:
27
+ if base.startswith("__"):
28
+ base = "Operation" + base
29
+ name = base
30
+ index = 2
31
+ while name in self.used:
32
+ name = f"{base}_{index}"
33
+ index += 1
34
+ self.used.add(name)
35
+ return name
36
+
37
+
38
+ def dictionary(name: str, items: Iterable[tuple[str, str, bool]]) -> str:
39
+ lines = []
40
+ for key, annotation, required in items:
41
+ item = repr(annotation) if required else f"t.NotRequired[{annotation!r}]"
42
+ lines.append(f" {key!r}: {item},")
43
+ return f"{name} = t.TypedDict({name!r}, {{\n" + "\n".join(lines) + "\n})"
44
+
45
+
46
+ def annotation(
47
+ type_: GraphQLType,
48
+ leaf: str,
49
+ *,
50
+ variables: bool = False,
51
+ ) -> str:
52
+ nullable = not isinstance(type_, GraphQLNonNull)
53
+ inner = type_ if nullable else type_.of_type
54
+ if isinstance(inner, GraphQLList):
55
+ result = f"list[{annotation(inner.of_type, leaf, variables=variables)}]"
56
+ else:
57
+ result = leaf
58
+ if nullable:
59
+ result += " | None"
60
+ if variables:
61
+ result += " | Variable"
62
+ return result
63
+
64
+
65
+ def scalar(type_: GraphQLNamedType, *, input_: bool) -> str:
66
+ if isinstance(type_, GraphQLEnumType):
67
+ values = ", ".join(repr(value) for value in type_.values)
68
+ return f"t.Literal[{values}]"
69
+ return {
70
+ "ID": "str | int" if input_ else "str",
71
+ "String": "str",
72
+ "Boolean": "bool",
73
+ "Int": "int",
74
+ "Float": "float",
75
+ }.get(type_.name, "t.Any")
76
+
77
+
78
+ class Inputs:
79
+ def __init__(self, schema: GraphQLSchema, names: Names, *, authoring: bool):
80
+ self.authoring = authoring
81
+ objects = [
82
+ t for t in schema.type_map.values() if isinstance(t, GraphQLInputObjectType)
83
+ ]
84
+ self.names = {obj.name: names.take(f"{obj.name}Input") for obj in objects}
85
+ self.definitions = [
86
+ dictionary(self.names[obj.name], self.items(obj.fields)) for obj in objects
87
+ ]
88
+
89
+ def type(self, type_: GraphQLType) -> str:
90
+ node = get_named_type(type_)
91
+ leaf = self.names.get(node.name) or scalar(node, input_=True)
92
+
93
+ return annotation(type_, leaf, variables=self.authoring)
94
+
95
+ def items(
96
+ self, fields: Mapping[str, GraphQLArgument | GraphQLInputField]
97
+ ) -> Iterable[tuple[str, str, bool]]:
98
+ for name, field in fields.items():
99
+ required = (
100
+ isinstance(field.type, GraphQLNonNull)
101
+ and field.default_value is Undefined
102
+ )
103
+ yield name, self.type(field.type), required
104
+
105
+
106
+ def render_schema(schema: GraphQLSchema) -> str:
107
+ names = Names()
108
+ inputs = Inputs(schema, names, authoring=True)
109
+ objects = [
110
+ obj
111
+ for obj in schema.type_map.values()
112
+ if isinstance(obj, GraphQLObjectType) and not obj.name.startswith("__")
113
+ ]
114
+ fields = {obj.name: names.take(f"{obj.name}Fields") for obj in objects}
115
+ definitions = [
116
+ "import typing as t\nfrom graphql_typed import Operation, Variable",
117
+ *inputs.definitions,
118
+ ]
119
+ leaf_selection = names.take("LeafSelection")
120
+ definitions.append(dictionary(leaf_selection, [("alias", "str", False)]))
121
+ leaf = f"t.Literal[True] | {leaf_selection}"
122
+ leaves = f"{leaf} | list[{leaf}]"
123
+ for obj in objects:
124
+ items = [("__typename", leaves, False)]
125
+ for key, field in obj.fields.items():
126
+ target = get_named_type(field.type)
127
+ if is_abstract_type(target):
128
+ continue
129
+ if not field.args and not isinstance(target, GraphQLObjectType):
130
+ items.append((key, leaves, False))
131
+ continue
132
+ options = [("alias", "str", False)]
133
+ required_args = False
134
+ if field.args:
135
+ args = names.take(f"{obj.name}_{key}Args")
136
+ members = list(inputs.items(field.args))
137
+ definitions.append(dictionary(args, members))
138
+ required_args = any(required for _, _, required in members)
139
+ options.append(("args", args, required_args))
140
+ if isinstance(target, GraphQLObjectType):
141
+ options.append(("select", fields[target.name], True))
142
+ selection = names.take(f"{obj.name}_{key}Selection")
143
+ definitions.append(dictionary(selection, options))
144
+ single = selection
145
+ if not required_args and not isinstance(target, GraphQLObjectType):
146
+ single = f"t.Literal[True] | {single}"
147
+ items.append((key, f"{single} | list[{single}]", False))
148
+ definitions.append(dictionary(fields[obj.name], items))
149
+
150
+ for kind, root in [
151
+ ("query", schema.query_type),
152
+ ("mutation", schema.mutation_type),
153
+ ]:
154
+ if root:
155
+ definitions.append(
156
+ f"def {kind}(name: str, *, select: {fields[root.name]}) -> Operation:\n"
157
+ f" return Operation({kind!r}, name, select)"
158
+ )
159
+ return "\n\n".join(definitions) + "\n"
@@ -0,0 +1,65 @@
1
+ """Publish a validated batch of generated files together across competing writers."""
2
+
3
+ import os
4
+ from collections.abc import Generator
5
+ from contextlib import contextmanager
6
+ from pathlib import Path
7
+
8
+ HEADER = b"# Generated by graphql-typed.\n"
9
+
10
+
11
+ @contextmanager
12
+ def _output_lock(output: Path) -> Generator[None, None, None]:
13
+ # OS locks are released if a generator process exits unexpectedly.
14
+ if os.name == "nt":
15
+ import msvcrt
16
+
17
+ cache = output / "__pycache__"
18
+ cache.mkdir(exist_ok=True)
19
+ with (cache / "graphql-typed.lock").open("a+b") as lock:
20
+ msvcrt.locking(lock.fileno(), msvcrt.LK_LOCK, 1)
21
+ yield
22
+ else:
23
+ import fcntl
24
+
25
+ fd = os.open(output, os.O_RDONLY)
26
+ try:
27
+ fcntl.flock(fd, fcntl.LOCK_EX)
28
+ yield
29
+ finally:
30
+ os.close(fd)
31
+
32
+
33
+ def publish(stage: Path, output: Path) -> None:
34
+ output.mkdir(exist_ok=True)
35
+ with _output_lock(output):
36
+ changed: dict[Path, bytes | None] = {}
37
+ for file in sorted(stage.iterdir()):
38
+ if not file.is_file():
39
+ continue
40
+ dest = output / file.name
41
+ previous = dest.read_bytes() if dest.exists() else None
42
+ if previous and not previous.startswith(HEADER):
43
+ raise ValueError(f"Refusing to replace user file {dest}")
44
+ if file.suffix == ".py":
45
+ file.write_bytes(HEADER + file.read_bytes())
46
+ if previous != file.read_bytes():
47
+ changed[file] = previous
48
+
49
+ written = []
50
+ try:
51
+ for file in changed:
52
+ file.replace(output / file.name)
53
+ written.append(file)
54
+ for cache in (output / "__pycache__").glob(f"{file.stem}.*.pyc"):
55
+ cache.unlink(missing_ok=True)
56
+ except BaseException:
57
+ for file in reversed(written):
58
+ dest = output / file.name
59
+ original = changed[file]
60
+ if original is None:
61
+ dest.unlink()
62
+ else:
63
+ file.write_bytes(original)
64
+ file.replace(dest)
65
+ raise
graphql_typed/py.typed ADDED
File without changes
@@ -0,0 +1,124 @@
1
+ """Transport contracts and execution shared by the generated clients."""
2
+
3
+ from collections.abc import Mapping
4
+ from typing import Any, Protocol
5
+
6
+
7
+ class Transport(Protocol):
8
+ def execute(
9
+ self, *, document: str, operation_name: str, variables: Mapping[str, object]
10
+ ) -> object: ...
11
+
12
+
13
+ class AsyncTransport(Protocol):
14
+ async def execute(
15
+ self, *, document: str, operation_name: str, variables: Mapping[str, object]
16
+ ) -> object: ...
17
+
18
+
19
+ class GraphQLResponseError(Exception):
20
+ def __init__(self, errors: list[Any], data: object) -> None:
21
+ self.errors = errors
22
+ self.data = data
23
+ super().__init__(
24
+ "; ".join(
25
+ str(e.get("message", e)) if isinstance(e, dict) else str(e)
26
+ for e in errors
27
+ )
28
+ )
29
+
30
+
31
+ def _data(response: object) -> dict[str, Any]:
32
+ if not isinstance(response, dict):
33
+ raise TypeError("Expected a GraphQL response object")
34
+ if "errors" in response:
35
+ errors = response["errors"]
36
+ if not isinstance(errors, list) or not errors:
37
+ raise ValueError("Expected a nonempty list of GraphQL errors")
38
+ raise GraphQLResponseError(errors, response.get("data"))
39
+ data = response.get("data")
40
+ if not isinstance(data, dict):
41
+ raise TypeError("Expected a GraphQL data object")
42
+ return data
43
+
44
+
45
+ def _payload(
46
+ document: str, name: str, variables: Mapping[str, object]
47
+ ) -> dict[str, object]:
48
+ return {"query": document, "operationName": name, "variables": dict(variables)}
49
+
50
+
51
+ class SyncExecutor:
52
+ def __init__(
53
+ self, endpoint: str | None = None, *, transport: Transport | None = None
54
+ ):
55
+ if transport is None and not endpoint:
56
+ raise ValueError("Supply an endpoint or a transport")
57
+ self._endpoint = endpoint
58
+ self._transport = transport
59
+
60
+ def _bind(self, name: str, documents: dict[str, str]):
61
+ document = documents[name]
62
+
63
+ def run(*, variables: Mapping[str, object] | None = None):
64
+ values = variables if variables is not None else {}
65
+ if self._transport is not None:
66
+ response = self._transport.execute(
67
+ document=document, operation_name=name, variables=values
68
+ )
69
+ else:
70
+ import httpx
71
+
72
+ assert self._endpoint is not None
73
+ result = httpx.post(
74
+ self._endpoint, json=_payload(document, name, values)
75
+ )
76
+ response = _http_response(result)
77
+ return _data(response)
78
+
79
+ return run
80
+
81
+
82
+ def _http_response(result: Any) -> object:
83
+ if not result.is_success:
84
+ try:
85
+ body = result.json()
86
+ except ValueError:
87
+ result.raise_for_status()
88
+ raise
89
+ if isinstance(body, dict) and body.get("errors"):
90
+ return body
91
+ result.raise_for_status()
92
+ return result.json()
93
+
94
+
95
+ class AsyncExecutor:
96
+ def __init__(
97
+ self, endpoint: str | None = None, *, transport: AsyncTransport | None = None
98
+ ):
99
+ if transport is None and not endpoint:
100
+ raise ValueError("Supply an endpoint or a transport")
101
+ self._endpoint = endpoint
102
+ self._transport = transport
103
+
104
+ def _bind(self, name: str, documents: dict[str, str]):
105
+ document = documents[name]
106
+
107
+ async def run(*, variables: Mapping[str, object] | None = None):
108
+ values = variables if variables is not None else {}
109
+ if self._transport is not None:
110
+ response = await self._transport.execute(
111
+ document=document, operation_name=name, variables=values
112
+ )
113
+ else:
114
+ import httpx
115
+
116
+ assert self._endpoint is not None
117
+ async with httpx.AsyncClient() as client:
118
+ result = await client.post(
119
+ self._endpoint, json=_payload(document, name, values)
120
+ )
121
+ response = _http_response(result)
122
+ return _data(response)
123
+
124
+ return run
@@ -0,0 +1,141 @@
1
+ Metadata-Version: 2.5
2
+ Name: graphql-typed-python
3
+ Version: 0.1.2
4
+ Summary: Generate typed GraphQL selections, variables, and response dictionaries for Python.
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.12
8
+ Requires-Dist: graphql-core<3.3,>=3.2.6
9
+ Provides-Extra: httpx
10
+ Requires-Dist: httpx>=0.28.1; extra == 'httpx'
11
+ Description-Content-Type: text/markdown
12
+
13
+ # graphql-typed-python
14
+
15
+ Build GraphQL operations with Python dictionary literals and get static types for both the request and the selected response fields. Generation has two passes. The schema supplies completions while you write your operations. Each named operation then supplies the variables and return type for the generated client.
16
+
17
+ ## Quick start
18
+
19
+ Use Python 3.12 or newer. Install the generator in your development environment. Applications using the default HTTP transport also need `httpx`.
20
+
21
+ ```sh
22
+ uv add --dev graphql-typed-python
23
+ uv add httpx
24
+ ```
25
+
26
+ Given a `schema.graphql` file:
27
+
28
+ ```graphql
29
+ type Query { device(serial: String!): Device }
30
+ type Device { id: ID!, name: String!, firmware: String }
31
+ ```
32
+
33
+ Generate the authoring types:
34
+
35
+ ```sh
36
+ uv run graphql-typed generate schema.graphql --out generated
37
+ ```
38
+
39
+ Write `operations.py` alongside the generated package:
40
+
41
+ ```python
42
+ from generated import schema
43
+ from graphql_typed import Operation, var
44
+
45
+ identity: schema.DeviceFields = {"id": True, "name": True}
46
+
47
+
48
+ def operations() -> list[Operation]:
49
+ return [
50
+ schema.query(
51
+ "DeviceBySerial",
52
+ select={
53
+ "device": {
54
+ "args": {"serial": var("serial")},
55
+ "select": identity,
56
+ },
57
+ },
58
+ )
59
+ ]
60
+ ```
61
+
62
+ Generate the client. This command also works on a fresh checkout. The generator evaluates the factory against the newly generated schema types before writing its outputs.
63
+
64
+ ```sh
65
+ uv run graphql-typed generate schema.graphql --out generated --operations operations:operations
66
+ ```
67
+
68
+ Use the same name to execute the operation:
69
+
70
+ ```python
71
+ from generated.client import AsyncClient
72
+
73
+
74
+ async def device_name(client: AsyncClient, serial: str) -> str | None:
75
+ data = await client.query("DeviceBySerial")(variables={"serial": serial})
76
+ if (device := data["device"]) is not None:
77
+ return device["name"]
78
+ return None
79
+ ```
80
+
81
+ Construct a client with `AsyncClient("https://example.test/graphql")`. The sync equivalent is `Client(endpoint).query("DeviceBySerial")(variables={"serial": "R42"})`. Completion follows the selected fields. Accessing `device["firmware"]` in this example is a type error.
82
+
83
+ ## Selections and variables
84
+
85
+ - Use `True` for a leaf field, `args` for field arguments, and `select` for nested fields. Object selections must contain at least one field.
86
+ - Use either a single selection or a list for each field. An alias becomes the key in the result. For example, `"name": [{"alias": "label"}]` yields `device["label"]`. Give distinct aliases to fields with different arguments.
87
+ - Use `var("name")` at an argument, input object field, or list item. The first use determines its GraphQL type. Further uses must have exactly the same type, including nullability and list markers. Custom scalars retain their GraphQL names and use Python `Any`.
88
+ - Input objects are dictionaries and enum values are string literals. Nullable variables can be omitted or set to `None`. A selected nullable response field has a required key whose value can be `None`.
89
+ - Use `schema.mutation(...)` and `client.mutation("Name")(...)` for mutations. Operations without variables are called as `client.query("Name")()`.
90
+ - V1 supports queries and mutations over concrete objects. Subscriptions, directives on selections, and type-specific selections on unions and interfaces are outside its scope.
91
+
92
+ ## Schema sources and output
93
+
94
+ The source can be an SDL file, a local introspection JSON document (raw or wrapped in `data`), or an HTTP(S) GraphQL endpoint. Endpoint generation issues an unauthenticated introspection request. Add `--no-ssl` to disable certificate verification for that request.
95
+
96
+ ```sh
97
+ uv run graphql-typed generate https://example.test/graphql --out generated --operations operations:operations
98
+ ```
99
+
100
+ For programmatic use, import `generate` from `graphql_typed.generator`. It accepts `source`, `out`, and the optional keyword arguments `operations` and `verify_ssl`. The factory reference uses `module:function` and the module must be importable.
101
+
102
+ | Generated module | Contents |
103
+ | --- | --- |
104
+ | `generated.schema` | Authoring types and operation builders. Used during development and generation. |
105
+ | `generated.client` | Sync and async clients with operation-name overloads. |
106
+ | `generated.types` | Input objects, per-operation variables, and response dictionaries. |
107
+ | `generated.transport` | Structural transport protocols and `GraphQLResponseError`. |
108
+
109
+ ## Transports and errors
110
+
111
+ The default transport posts GraphQL JSON using `httpx`. To supply a transport, implement the following method and pass the object to the client. An async transport provides an `async def execute` method with the same parameters.
112
+
113
+ ```python
114
+ from collections.abc import Mapping
115
+ from generated.client import Client
116
+
117
+
118
+ class FakeTransport:
119
+ def execute(
120
+ self, *, document: str, operation_name: str, variables: Mapping[str, object]
121
+ ) -> object:
122
+ return {"data": {"device": {"id": "42", "name": "router"}}}
123
+
124
+
125
+ client = Client(transport=FakeTransport())
126
+ ```
127
+
128
+ A transport returns the decoded GraphQL response envelope. The client returns its `data` on success. When the envelope contains errors, it raises `generated.transport.GraphQLResponseError` with `.errors` and `.data`, including any partial result. Consumers using a custom transport can run the generated client with the Python standard library alone.
129
+
130
+ ## Development
131
+
132
+ ```sh
133
+ uv sync --locked
134
+ prek install
135
+ prek run --all-files
136
+ uv build
137
+ ```
138
+
139
+ Small schemas, operation factories, and `typing.assert_type` examples live in `tests/contract/`. The tests generate clients in temporary packages, check them with `ty`, exercise editor completions via its language server, and execute queries through custom transports and a local GraphQL HTTP server. The TLS test uses the `openssl` command. `just check` runs the same formatting, typing, and test checks used in CI.
140
+
141
+ The release workflow builds and checks distributions on pushes to the `releases` branch and publishes using PyPI trusted publishing. `just release` runs local release checks and pushes the version bump.
@@ -0,0 +1,17 @@
1
+ graphql_typed/__init__.py,sha256=CzBPqfi6kzuy_596KYg-6V-cuM2KcrLdGziY5YiWfqw,370
2
+ graphql_typed/cli.py,sha256=jqc_NqzM6YLIRsKQeQP0nYDzNhPTZ0ixWbUxPof0mIU,1202
3
+ graphql_typed/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ graphql_typed/generator/__init__.py,sha256=3tzbT79j_ySBO1BIYfsegpru-28RJppK90piTeXRXQs,38
5
+ graphql_typed/generator/api.py,sha256=1bpZhyIv-nBSlrtTjmWyTF1t9BXOhKqWO7Z6mpL6jNg,2300
6
+ graphql_typed/generator/client.py,sha256=vzzZ_269S1wiHDRwxbUzGE7a_s-FBUUJPk69nGXHBVs,4941
7
+ graphql_typed/generator/factory.py,sha256=lpKC0UKcUdZOzzUCrvinCCcRxvsFR52zE5uPg6LSVOM,1589
8
+ graphql_typed/generator/loader.py,sha256=gZDy_BsMZuap_B_dMJi_6oZ5iBKBhZUpv9WP_J_hQoQ,1422
9
+ graphql_typed/generator/operations.py,sha256=Bg5RH9PUdoXA7ZxOAhv1lGTXYA8oYWJdcJoOEmBFQ8s,5971
10
+ graphql_typed/generator/types.py,sha256=k9xFs8n1Ds_eWV26XMjsz9JpCoAORPlJ7ppVBZxmgoI,5505
11
+ graphql_typed/generator/write.py,sha256=yaGhmm67tGRDS0RD80Y9jJDVLMFVJfUbSGCO1kplAB0,2180
12
+ graphql_typed/templates/transport.py,sha256=QsNa-YwoXF4KEEwo-6vXPSQ6PGbpqGJWftC5fcbZ30s,4098
13
+ graphql_typed_python-0.1.2.dist-info/METADATA,sha256=3eNNb_JRv4PylJOwXcid0kiRzwxsEjGEz01hVciIAeE,6509
14
+ graphql_typed_python-0.1.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
15
+ graphql_typed_python-0.1.2.dist-info/entry_points.txt,sha256=ftNhHj6Pmy6vjE1fqbw3X6BdGruTuhezQpGKv516YKI,57
16
+ graphql_typed_python-0.1.2.dist-info/licenses/LICENSE,sha256=rgF1PgtpknpJGs3-6ZTTmwMQPdLOPkve2vLlCCldM7E,1069
17
+ graphql_typed_python-0.1.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ graphql-typed = graphql_typed.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Anders Brams
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.