API Reference
Protocols
Section titled “Protocols”PersistedQueryStore
Section titled “PersistedQueryStore”Store for persisted query mappings.
Implement this protocol to provide custom storage for persisted queries.
Get a query by its hash.
| Parameter | Type | Description |
|---|---|---|
| `hash` | str | SHA256 hash of the query. |
| Type | Description |
|---|---|
| str | None | The query string if found, None otherwise. |
Store a query with its hash.
| Parameter | Type | Description |
|---|---|---|
| `hash` | str | SHA256 hash of the query. |
| `query` | str | The full query string. |
Classes
Section titled “Classes”APQHandler
Section titled “APQHandler”Handler for Automatic Persisted Queries.
Implements the APQ protocol:
- Client sends query hash → Server looks up full query
- If not found, client sends hash + full query → Server stores
- Subsequent requests use just the hash
def __init__( store: PersistedQueryStore, enabled: bool = True )
Initialize the APQ handler.
| Parameter | Type | Description |
|---|---|---|
| `store` | PersistedQueryStore | Persisted query store implementation. |
| `enabled` | bool | Whether APQ is enabled. |
Check if APQ is enabled.
async def resolve_query( query: str | None, extensions: dict | None = None ) -> APQResult
Resolve the full query using APQ.
| Parameter | Type | Description |
|---|---|---|
| `query` | str | None | The query from the request (may be None for hash-only). |
| `extensions` | dict | None | The extensions from the GraphQL request. |
| Type | Description |
|---|---|
| APQResult | APQResult with the resolved query. |
Create the APQ extension response.
| Parameter | Type | Description |
|---|---|---|
| `hash` | str | The query hash. |
| Type | Description |
|---|---|
| dict | Extension dict for the GraphQL response. |
APQResult
Section titled “APQResult”Result of APQ lookup.
Attributes: query: The full query string (if found). is_persisted: Whether the query was found in the store. hash: The hash used for lookup.
AbstractPermission
Section titled “AbstractPermission”Base class for GraphQL permissions.
Permission classes control access to GraphQL fields. They are checked before field resolution and can raise exceptions or return False to deny access.
Attributes: message: Error message when permission is denied.
Example
class IsAuthenticated(AbstractPermission): message = "Authentication required"
async def has_permission(self, source, info, **kwargs): return info.context.user is not None
@strawberry.typeclass User: @field(permission_classes=[IsAuthenticated]) async def email(self) -> str: return self._emailCheck if the permission is granted.
| Parameter | Type | Description |
|---|---|---|
| `source` | Any | The source object (parent resolver result). |
| `info` | Info | GraphQL resolver info containing context. **kwargs: Additional arguments passed to the field. |
| Type | Description |
|---|---|
| bool | True if permission is granted, False otherwise. |
| Exception | Description |
|---|---|
| Exception | If permission is denied with a custom error. |
AfterExecuteEvent
Section titled “AfterExecuteEvent”Emitted after a GraphQL operation completes successfully.
Contains the execution context with timing information and the raw response.
AliasLimitValidator
Section titled “AliasLimitValidator”Validate query alias count against a limit.
Analyzes GraphQL queries to count aliases and validates against a configured maximum.
Example
validator = AliasLimitValidator(max_aliases=10)
count = validator.count_aliases(document)validator.validate(document) # Raises if too manyInitialize the validator.
| Parameter | Type | Description |
|---|---|---|
| `max_aliases` | int | Maximum allowed aliases. |
Get maximum alias limit.
Count the number of aliases in a query.
| Parameter | Type | Description |
|---|---|---|
| `document` | DocumentNode | Parsed GraphQL document. |
| Type | Description |
|---|---|
| int | Number of aliases. |
Validate alias count.
| Parameter | Type | Description |
|---|---|---|
| `document` | DocumentNode | Parsed GraphQL document. |
| Exception | Description |
|---|---|
| SecurityError | If query has too many aliases. |
AllowAny
Section titled “AllowAny”Permission that allows any access (no restrictions).
Always allow access.
BeforeExecuteEvent
Section titled “BeforeExecuteEvent”Emitted immediately before a GraphQL operation is sent to Strawberry.
Subscribers may inspect the execution context (query, variables, user) but must NOT modify it — the event is immutable by design.
CacheBackendPersistedQueryStore
Section titled “CacheBackendPersistedQueryStore”CacheBackendProtocol-backed APQ store for multi-process deployments.
Uses the platform’s CacheBackendProtocol abstraction rather than a raw Redis client — compatible with any configured cache provider (Redis, Memcached, etc.) without coupling this package to a specific driver.
Suitable for production use with multiple application instances.
Initialize the store.
| Parameter | Type | Description |
|---|---|---|
| `cache` | Any | A CacheBackendProtocol instance. |
| `key_prefix` | str | Prefix applied to all cache keys. |
| `ttl_seconds` | int | Time-to-live for stored entries in seconds. |
Get a query by its hash.
Store a query with its hash.
CacheConfig
Section titled “CacheConfig”Cache configuration for GraphQL responses.
Attributes: enabled: Whether caching is enabled. default_max_age: Default cache duration in seconds. default_scope: Default cache scope (PUBLIC/PRIVATE). vary_headers: Headers to vary cache on.
CacheControl
Section titled “CacheControl”Cache control settings for a field or type.
CacheScope
Section titled “CacheScope”Cache control scope for responses.
Connection
Section titled “Connection”GraphQL Connection type template for cursor-based pagination.
This is a generic template. Use create_connection_type() to create concrete Connection types for your node types.
Attributes: edges: List of edges containing nodes. page_info: Pagination information. total_count: Total number of items.
ContextFactory
Section titled “ContextFactory”Factory for creating GraphQL contexts.
Provides a standardized way to create execution contexts with proper initialization and DataLoaderProtocol setup.
def __init__( config: GraphQLConfig | None = None, dataloader_factories: dict[str, Any] | None = None, enable_identity_resolution: bool | None = None, resolver: Any | None = None ) -> None
Initialize the context factory.
| Parameter | Type | Description |
|---|---|---|
| `config` | GraphQLConfig | None | GraphQL configuration. |
| `dataloader_factories` | dict[str, Any] | None | Factory functions for DataLoaders. |
| `enable_identity_resolution` | bool | None | Whether to automatically resolve OAuth IDs to UUIDs. If not provided, reads from config if available, otherwise defaults to False (opt-in). |
| `resolver` | Any | None | Optional DI resolver to use for identity resolution. |
async def create_context( request: GraphQLRequest | None = None, user: Any | None = None, metadata: dict[str, Any] | None = None, raw_request: Any | None = None ) -> GraphQLContext
Create a new GraphQL context.
This async version properly resolves OAuth external IDs to internal UUIDs if the OAuthIdentityStore is available in the container, and optionally authenticates and resolves a principal.
Authentication flow:
- If user is provided, use it directly (middleware-authenticated)
- If no user but raw_request is available, optionally authenticate
- Resolve principal via GraphQLPrincipalResolverProtocol
- If no resolver exists but user is present, create fallback principal
| Parameter | Type | Description |
|---|---|---|
| `request` | GraphQLRequest | None | The GraphQL request. |
| `user` | Any | None | Current user (from middleware or previous auth). |
| `metadata` | dict[str, Any] | None | Additional metadata. |
| `raw_request` | Any | None | The raw HTTP request. |
| Type | Description |
|---|---|
| GraphQLContext | A new GraphQLContext instance with resolved user ID and principal. |
def create_context_sync( request: GraphQLRequest | None = None, user: Any | None = None, metadata: dict[str, Any] | None = None, raw_request: Any | None = None ) -> GraphQLContext
Create a GraphQL context synchronously (testing/sync-bridge only).
Warning Prefer create_context in production code. This method does not perform async identity resolution or principal resolution — the
userobject is passed through as-is and principal is set to None. Use only in test environments or sync integration points that cannotawait.
| Parameter | Type | Description |
|---|---|---|
| `request` | GraphQLRequest | None | The GraphQL request. |
| `user` | Any | None | Current user (no async identity resolution performed). |
| `metadata` | dict[str, Any] | None | Additional metadata. |
| `raw_request` | Any | None | The raw HTTP request. |
| Type | Description |
|---|---|
| GraphQLContext | A new GraphQLContext instance without async identity or principal resolution. |
Register a DataLoaderProtocol factory.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | DataLoaderProtocol name. |
| `factory` | Any | Factory function that creates the DataLoaderProtocol. |
def from_dict( data: dict[str, Any], request: GraphQLRequest | None = None ) -> GraphQLContext
Create a GraphQLContext from a plain dictionary.
A convenience factory for callers that previously passed dict
directly to GraphQLExecutorProtocol.execute. Extracts user,
metadata, and optionally request from data.
| Parameter | Type | Description |
|---|---|---|
| `data` | dict[str, Any] | Mapping with optional keys ``user``, ``metadata``, and ``request``. |
| `request` | GraphQLRequest | None | Explicit request object; overrides ``data["request"]`` when provided. |
| Type | Description |
|---|---|
| GraphQLContext | A fully initialised GraphQLContext. |
Example
context = ContextFactory.from_dict( {"user": current_user, "metadata": {"source": "api"}},)result = await executor.execute(query, context=context)CursorConnection
Section titled “CursorConnection”A connection for cursor-based pagination.
CursorPaginationInput
Section titled “CursorPaginationInput”Input for cursor-based pagination.
Attributes: first: Number of items to fetch from the start. after: Cursor to fetch items after. last: Number of items to fetch from the end. before: Cursor to fetch items before.
DataLoaderConfig
Section titled “DataLoaderConfig”DataLoaderProtocol configuration.
Attributes: enabled: Whether DataLoaderProtocol integration is enabled. batch_enabled: Whether batching is enabled. cache_enabled: Whether per-request caching is enabled. max_batch_size: Maximum batch size for DataLoaderProtocol. batch_schedule_fn: How to schedule batch execution.
DataLoaderProtocol
Section titled “DataLoaderProtocol”DataLoaderProtocol for batching and caching.
DataLoaderProtocol is a utility for batching and caching data fetches to efficiently resolve GraphQL queries and avoid the N+1 problem.
Example
async def batch_load_users(ids: list[str]) -> list[User | None]: users = await db.get_users_by_ids(ids) # Return in same order as input ids user_map = {u.id: u for u in users} return list(map(lambda id: user_map.get(id), ids))
loader = DataLoaderProtocol(batch_load_users)
# These will be batched into a single calluser1 = await loader.load("1")user2 = await loader.load("2")def __init__( batch_fn: Callable[[list[K]], Awaitable[list[V | None]]], config: DataLoaderConfig | None = None, cache: LoaderCache[K, V] | None = None ) -> None
Initialize the DataLoaderProtocol.
| Parameter | Type | Description |
|---|---|---|
| `batch_fn` | Callable[[list[K]], Awaitable[list[V | None]]] | Function that loads a batch of values by keys. |
| `config` | DataLoaderConfig | None | DataLoaderProtocol configuration. |
| `cache` | LoaderCache[K, V] | None | Optional cache implementation. |
property config() -> DataLoaderConfig
Get configuration.
Load a value by key.
The load will be batched with other loads that occur in the same tick of the event loop.
| Parameter | Type | Description |
|---|---|---|
| `key` | K | The key to load. |
| Type | Description |
|---|---|
| V | None | The loaded value or None if not found. |
| Exception | Description |
|---|---|
| DataLoaderError | If loading fails. |
Load multiple values by keys.
| Parameter | Type | Description |
|---|---|---|
| `keys` | Sequence[K] | List of keys to load. |
| Type | Description |
|---|---|
| list[V | None] | List of values in the same order as keys. |
Prime the cache with a value.
Use this to add values to the cache that were loaded through other means.
| Parameter | Type | Description |
|---|---|---|
| `key` | K | The key. |
| `value` | V | The value to cache. |
Clear a cached value.
| Parameter | Type | Description |
|---|---|---|
| `key` | K | The key to clear. |
Clear all cached values.
DataLoaderStats
Section titled “DataLoaderStats”Statistics for a DataLoaderProtocol instance.
DeleteResult
Section titled “DeleteResult”Result of a delete mutation.
Attributes: success: Whether deletion succeeded. id: ID of deleted item. message: Optional message.
DenyAll
Section titled “DenyAll”Permission that denies all access.
Always deny access.
DeprecationDirectiveHandler
Section titled “DeprecationDirectiveHandler”Marks targets as deprecated using the ``@deprecated`` directive.
Adds a __deprecated__ attribute with the deprecation reason to any
target object that supports attribute assignment.
Apply @deprecated by setting __deprecated__ on target.
| Parameter | Type | Description |
|---|---|---|
| `directive_name` | str | Expected to be ``"deprecated"``. |
| `args` | dict[str, Any] | May contain ``"reason"`` (str). |
| `target` | Any | Any object. |
| Type | Description |
|---|---|
| Any | The *target* with ``__deprecated__`` set. |
DepthLimitConfig
Section titled “DepthLimitConfig”Query depth limiting configuration.
Attributes: enabled: Whether depth limiting is enabled. max_depth: Maximum allowed query depth. ignore_introspection: Ignore introspection queries.
DepthLimitExtension
Section titled “DepthLimitExtension”Strawberry extension for query depth limiting.
Add this extension to your schema to automatically validate query depth before execution.
Example
from lexigram.graphql.security import DepthLimitExtension
schema = strawberry.Schema( query=Query, extensions=[DepthLimitExtension(max_depth=10)],)Initialize the extension.
| Parameter | Type | Description |
|---|---|---|
| `max_depth` | int | Maximum allowed query depth. |
| `ignore_introspection` | bool | Skip introspection queries. |
Hook called during operation execution.
DepthLimitValidator
Section titled “DepthLimitValidator”Validate query depth against a limit.
Analyzes GraphQL queries to determine their depth and validates against a configured maximum depth.
Example
validator = DepthLimitValidator(max_depth=10)
# Validate a parsed documentdepth = validator.get_depth(document)validator.validate(document) # Raises if too deepInitialize the validator.
| Parameter | Type | Description |
|---|---|---|
| `max_depth` | int | Maximum allowed query depth. |
| `ignore_introspection` | bool | Skip depth check for introspection queries. |
Get maximum depth limit.
Calculate the maximum depth of a query.
| Parameter | Type | Description |
|---|---|---|
| `document` | DocumentNode | Parsed GraphQL document. |
| Type | Description |
|---|---|
| int | Maximum depth of the query. |
Validate query depth.
| Parameter | Type | Description |
|---|---|---|
| `document` | DocumentNode | Parsed GraphQL document. |
| Exception | Description |
|---|---|
| DepthLimitError | If query exceeds depth limit. |
DirectiveLocation
Section titled “DirectiveLocation”GraphQL directive locations.
DirectiveRegistry
Section titled “DirectiveRegistry”Registry-based implementation of DirectiveHandler.
Maps directive names to handler callables via on (decorator syntax or explicit register call). When apply_directive is invoked with an unknown directive name, the target is returned unchanged if no default handler is registered, or the default handler is called.
| Parameter | Type | Description |
|---|---|---|
| `default_handler` | Optional fallback for unrecognised directives. Receives the same ``(directive_name, args, target)`` signature. When ``None`` (default), unknown directives are silently ignored. |
Register a handler callable for a directive.
| Parameter | Type | Description |
|---|---|---|
| `directive_name` | str | Name of the GraphQL directive (without ``@``). |
| `handler` | Any | Callable ``(directive_name, args, target) -> target``. |
Decorator that registers a handler for directive_name.
Example
@registry.on("auth")def apply_auth(name, args, target): target.__roles__ = args.get("roles", []) return target| Parameter | Type | Description |
|---|---|---|
| `directive_name` | str | Name of the directive. |
| Type | Description |
|---|---|
| Any | Decorator that registers the decorated function. |
Apply a registered directive handler to target.
If no handler is registered under directive_name the default handler is called if one was supplied; otherwise target is returned as-is.
| Parameter | Type | Description |
|---|---|---|
| `directive_name` | str | Directive to apply (without ``@``). |
| `args` | dict[str, Any] | Directive arguments from the schema. |
| `target` | Any | Schema element to transform. |
| Type | Description |
|---|---|
| Any | The (possibly transformed) *target*. |
An edge in a connection.
ErrorConfig
Section titled “ErrorConfig”Error handling configuration.
Attributes: mask_errors: Whether to mask internal errors in production. include_stacktrace: Whether to include stacktrace in errors. debug_mode: Whether debug mode is enabled. log_errors: Whether to log errors.
ExecutionContextProtocol
Section titled “ExecutionContextProtocol”Context for a single query execution.
Tracks execution state, metrics, and provides hooks for middleware and extensions.
Attributes: context: The GraphQL context. operation_type: Type of operation being executed. start_time: Execution start time. end_time: Execution end time. errors: Errors encountered during execution. extensions: Execution extensions data.
Mark execution as complete.
Get execution duration in milliseconds.
Add an error to the execution context.
Check if execution has errors.
ExecutionTrace
Section titled “ExecutionTrace”Complete execution trace.
Attributes: operation_name: Name of the operation. start_time: Execution start time. end_time: Execution end time. total_duration_ms: Total duration. root_span: Root span of the trace. resolver_count: Number of resolvers called.
End the trace.
Convert to dictionary.
| Type | Description |
|---|---|
| dict[str, Any] | Dictionary representation (Apollo tracing format). |
FieldInfo
Section titled “FieldInfo”Information about a GraphQL field.
GraphQLConfig
Section titled “GraphQLConfig”Hierarchical root configuration for Lexigram GraphQL.
Attributes: name: Configuration name (default: “graphql”) enabled: Whether GraphQL module is enabled path: GraphQL endpoint path debug: Platform debug flag (aligns with ObservabilityConfig.debug). Propagates to errors.debug_mode. enable_identity_resolution: Resolve OAuth IDs to internal UUIDs cache: Response caching settings depth_limit: Query depth limiting complexity: Query complexity settings persisted_queries: Persisted queries settings batch: Batch query settings introspection: Introspection settings playground: GraphQL playground settings subscriptions: WebSocket subscription settings dataloader: DataLoaderProtocol settings tracing: Tracing settings metrics: Metrics settings error: Error handling settings rate_limit: Rate limiting settings
def development(cls) -> GraphQLConfig
Create development configuration with debugging enabled.
def production(cls) -> GraphQLConfig
Create production configuration with security hardening.
GraphQLContext
Section titled “GraphQLContext”GraphQL execution context.
Provides context for GraphQL operations including request information, user data, and configuration.
Attributes: request_id: Unique request identifier. user: Current user (if authenticated). principal: Resolved principal for identity access across resolvers. request: The GraphQL request. config: GraphQL configuration. started_at: Request start time. metadata: Additional context metadata. dataloaders: DataLoaderProtocol instances by name.
Get a DataLoaderProtocol by name.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | DataLoaderProtocol name. |
| Type | Description |
|---|---|
| Any | None | The DataLoaderProtocol instance or None. |
Set a DataLoaderProtocol.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | DataLoaderProtocol name. |
| `loader` | Any | DataLoaderProtocol instance. |
Get metadata value.
| Parameter | Type | Description |
|---|---|---|
| `key` | str | Metadata key. |
| `default` | Any | Default value if not found. |
| Type | Description |
|---|---|
| Any | The metadata value. |
Set metadata value.
| Parameter | Type | Description |
|---|---|---|
| `key` | str | Metadata key. |
| `value` | Any | Metadata value. |
Get the operation name from request.
Get variables from request.
Get elapsed time in milliseconds.
Dispose the per-request DI scope, releasing all scoped services.
No-op when no scope was created for this context. The GraphQL executor calls this automatically; application code should not normally need to call it directly.
GraphQLController
Section titled “GraphQLController”GraphQL HTTP endpoint controller.
This controller exposes GraphQL queries and mutations via HTTP POST
at the configured path (default: /graphql).
Example
Registration is handled automatically by the GraphQL provider.
To mount the controller manually, resolve the web application via the
HTTPApplicationProtocol from contracts — do not import from
lexigram.web directly
from lexigram.contracts.web.protocols import HTTPApplicationProtocol# app = await container.resolve(HTTPApplicationProtocol)# app.mount("/graphql", graphql_view)def __init__(provider: GraphQLProvider | None = None) -> None
Initialize the GraphQL controller.
| Parameter | Type | Description |
|---|---|---|
| `provider` | GraphQLProvider | None | GraphQL provider instance. If None, will be resolved from the DI container at request time. |
Collect routes from controller methods.
async def execute(request: GraphQLRequestProtocol) -> JSONResponse
Execute a GraphQL query.
| Parameter | Type | Description |
|---|---|---|
| `request` | GraphQLRequestProtocol | HTTP request containing the GraphQL query. |
| Type | Description |
|---|---|
| JSONResponse | JSON response with query results or errors. |
GraphQLErrorCode
Section titled “GraphQLErrorCode”Standard GraphQL error codes.
GraphQLErrorData
Section titled “GraphQLErrorData”Structured GraphQL error data.
GraphQLErrorExtensions
Section titled “GraphQLErrorExtensions”Extended error information.
GraphQLExecutorProtocol
Section titled “GraphQLExecutorProtocol”GraphQL query executor.
Provides a high-level interface for executing GraphQL operations with proper error handling, timeout support, and metrics collection.
Example
from strawberry import Schemafrom lexigram.graphql.core import GraphQLExecutorProtocol
schema = Schema(query=Query)executor = GraphQLExecutorProtocol(schema)
response = await executor.execute( query="{ hello }", variables={},)def __init__( schema: StrawberrySchema, timeout_secs: float | None = None, middleware: list[Callable[Ellipsis, Any]] | None = None, error_config: ErrorConfig | None = None, event_bus: EventBusProtocol | None = None ) -> None
Initialize the executor.
| Parameter | Type | Description |
|---|---|---|
| `schema` | StrawberrySchema | Strawberry GraphQL schema. |
| `timeout_secs` | float | None | Default timeout in seconds. |
| `middleware` | list[Callable[Ellipsis, Any]] | None | List of middleware functions. |
| `error_config` | ErrorConfig | None | Error configuration for formatting. |
| `event_bus` | EventBusProtocol | None | Optional EventBusProtocol for lifecycle event publishing. Subscribers receive BeforeExecuteEvent, AfterExecuteEvent, and OnErrorEvent. |
Get the GraphQL schema.
async def execute( query: str, variables: dict[str, Any] | None = None, operation_name: str | None = None, context: GraphQLContext | None = None, timeout_secs: float | None = None ) -> Result[GraphQLResponse[Any], Exception]
Execute a GraphQL query.
| Parameter | Type | Description |
|---|---|---|
| `query` | str | GraphQL query string. |
| `variables` | dict[str, Any] | None | Query variables. |
| `operation_name` | str | None | Operation name to execute. |
| `context` | GraphQLContext | None | GraphQL context. Use ContextFactory.from_dict to convert a plain dictionary before passing it here. |
| `timeout` | Timeout in seconds (overrides default). |
| Type | Description |
|---|---|
| Result[GraphQLResponse, Exception] | Result wrapping the response or an infrastructure error. |
| Exception | Description |
|---|---|
| None | Infrastructure errors are wrapped in Err. |
def get_metrics(execution_context: ExecutionContextProtocol) -> QueryMetrics
Get execution metrics.
| Parameter | Type | Description |
|---|---|---|
| `execution_context` | ExecutionContextProtocol | Execution context. |
| Type | Description |
|---|---|
| QueryMetrics | Query metrics. |
GraphQLLocation
Section titled “GraphQLLocation”Location in a GraphQL document.
GraphQLMetrics
Section titled “GraphQLMetrics”Aggregated GraphQL metrics.
Attributes: total_requests: Total number of requests. successful_requests: Number of successful requests. failed_requests: Number of failed requests. total_duration_ms: Total execution time. avg_duration_ms: Average execution time. operations_by_type: Count by operation type. operations_by_name: Count by operation name. errors_by_type: Error count by type.
def record_request(stats: QueryStats) -> None
Record a request’s statistics.
| Parameter | Type | Description |
|---|---|---|
| `stats` | QueryStats | Query statistics. |
Record an error.
| Parameter | Type | Description |
|---|---|---|
| `error_type` | str | Type of error. |
Convert to dictionary.
| Type | Description |
|---|---|
| dict[str, Any] | Dictionary representation. |
GraphQLModule
Section titled “GraphQLModule”GraphQL layer (Strawberry): schema building, execution, federation, and subscriptions.
Call configure to configure and mount the GraphQL endpoint.
Usage
import strawberry
@strawberry.typeclass Query: @strawberry.field def hello(self) -> str: return "world"
@module( imports=[GraphQLModule.configure(query_class=Query)])class AppModule(Module): passdef configure( cls, config: Any | None = None, query_class: Any | None = None, mutation_class: Any | None = None, subscription_class: Any | None = None ) -> DynamicModule
Create a GraphQLModule with explicit configuration.
| Parameter | Type | Description |
|---|---|---|
| `config` | Any | None | GraphQLConfig or ``None`` for framework defaults. |
| `query_class` | Any | None | Optional root Strawberry ``Query`` type. |
| `mutation_class` | Any | None | Optional root Strawberry ``Mutation`` type. |
| `subscription_class` | Any | None | Optional root Strawberry ``Subscription`` type. |
| Type | Description |
|---|---|
| DynamicModule | A DynamicModule descriptor. |
def stub(cls) -> DynamicModule
Return a no-op GraphQLModule suitable for unit testing.
Registers a GraphQLProvider with no schema types configured. Useful for testing application structure without a real GraphQL executor.
| Type | Description |
|---|---|
| DynamicModule | A DynamicModule with noop GraphQL configuration. |
GraphQLProvider
Section titled “GraphQLProvider”Provider for GraphQL functionality.
This provider integrates GraphQL capabilities into the Lexigram Framework, including schema building, execution, federation, and monitoring.
Features:
- GraphQL schema management and execution
- Apollo Federation support (subgraph)
- DataLoaderProtocol for batching and caching
- Query validation and depth limiting
- Metrics collection and tracing
- Subscription support
- Security features (rate limiting, auth)
Configuration: The provider is configured via GraphQLConfig in the application configuration. If no config is provided, sensible defaults are used.
Usage
app = Application()app.add_provider(GraphQLProvider())def __init__( config: GraphQLConfig | None = None, query_class: Any | None = None, mutation_class: Any | None = None, subscription_class: Any | None = None, priority: ProviderPriority = ProviderPriority.PRESENTATION ) -> None
Initialize the GraphQL provider.
| Parameter | Type | Description |
|---|---|---|
| `config` | GraphQLConfig | None | GraphQL configuration. If None, uses defaults. |
| `query_class` | Any | None | Optional GraphQL Query class. |
| `mutation_class` | Any | None | Optional GraphQL Mutation class. |
| `subscription_class` | Any | None | Optional GraphQL Subscription class. |
| `priority` | ProviderPriority | Provider priority for initialization order. |
def from_config( cls, config: GraphQLConfig, **context: Any ) -> GraphQLProvider
Create a GraphQLProvider from config.
Context kwargs may include query_class, mutation_class, subscription_class.
def auto_discover( cls, *packages: str, config: GraphQLConfig | None = None, **kwargs: Any ) -> GraphQLProvider
Create a GraphQLProvider by scanning packages for Strawberry types.
Scans each package recursively for classes decorated with
@strawberry.type whose name is Query, Mutation, or
Subscription. Use @strawberry.type plus the naming convention
or explicitly set __graphql_role__ = "query" / "mutation" /
"subscription" on the class to override the name-based detection.
| Parameter | Type | Description |
|---|---|---|
| `config` | GraphQLConfig | None | Optional GraphQLConfig. Falls back to framework defaults when not provided. **kwargs: Extra keyword arguments forwarded to GraphQLProvider.__init__. |
| Type | Description |
|---|---|
| GraphQLProvider | A configured GraphQLProvider instance. |
Example
app.add_provider(GraphQLProvider.auto_discover("my_app.graphql"))In my_app/graphql/schema.py
import strawberry
@strawberry.typeclass Query: @strawberry.field async def hello(self) -> str: return "world"
@strawberry.typeclass Mutation: @strawberry.mutation async def set_name(self, name: str) -> str: return nameasync def register(container: ContainerRegistrarProtocol) -> None
Register GraphQL services with the DI container.
| Parameter | Type | Description |
|---|---|---|
| `container` | ContainerRegistrarProtocol | The dependency injection container registrar. |
Initialize GraphQL components.
| Parameter | Type | Description |
|---|---|---|
| `container` | BootContainerProtocol | The application container resolver. |
def executor() -> GraphQLExecutorProtocol | None
Get the GraphQL executor instance.
property context_factory() -> ContextFactory | None
Get the GraphQL context factory instance.
Shutdown GraphQL components.
Check the health of GraphQL components.
| Type | Description |
|---|---|
| HealthCheckResult | Health check results. |
GraphQLRequest
Section titled “GraphQLRequest”GraphQL request model.
Represents an incoming GraphQL request with query, variables, and operation name.
Attributes: query: The GraphQL query string. variables: Variables for the query. operation_name: Name of the operation to execute. extensions: Optional extensions data.
GraphQLRequestReceivedHook
Section titled “GraphQLRequestReceivedHook”Payload fired when a GraphQL operation request is received.
Attributes:
operation_type: "query", "mutation", or "subscription".
operation_name: Named operation, if present in the document.
GraphQLResponse
Section titled “GraphQLResponse”GraphQL response model.
Represents a GraphQL response with data and/or errors.
Attributes: data: The result data. errors: List of errors if any occurred. extensions: Optional response extensions.
Check if response has errors.
Check if response is successful.
def add_error( message: str, path: list[str | int] | None = None, extensions: dict[str, Any] | None = None ) -> None
Add an error to the response.
| Parameter | Type | Description |
|---|---|---|
| `message` | str | Error message. |
| `path` | list[str | int] | None | Path to the error. |
| `extensions` | dict[str, Any] | None | Additional error data. |
GraphQLResponsePreparedHook
Section titled “GraphQLResponsePreparedHook”Payload fired after a GraphQL response has been assembled.
Attributes:
operation_type: "query", "mutation", or "subscription".
has_errors: True if the response contains any GraphQL errors.
GraphQLSchemaBuiltHook
Section titled “GraphQLSchemaBuiltHook”Payload fired after the GraphQL schema has been compiled and is ready.
GraphQLSubscriptionController
Section titled “GraphQLSubscriptionController”GraphQL WebSocket subscription controller.
This controller handles GraphQL subscriptions via WebSocket
at the configured path (default: /graphql/subscriptions).
def __init__(provider: GraphQLProvider | None = None) -> None
Initialize the subscription controller.
| Parameter | Type | Description |
|---|---|---|
| `provider` | GraphQLProvider | None | GraphQL provider instance. If None, will be resolved from the DI container at request time. |
Collect routes from controller methods.
InMemoryCache
Section titled “InMemoryCache”In-memory cache implementation.
Simple in-memory cache with optional TTL support. Suitable for single-request caching in DataLoaders.
Example
cache = InMemoryCache[str, User](ttl_seconds=60)
cache.set("user:1", user)user = cache.get("user:1")Initialize the cache.
| Parameter | Type | Description |
|---|---|---|
| `ttl_seconds` | float | Time-to-live in seconds (0 for no TTL). |
| `max_size` | int | Maximum cache size (0 for unlimited). |
Get current cache size.
Get a cached value.
| Parameter | Type | Description |
|---|---|---|
| `key` | K | Cache key. |
| Type | Description |
|---|---|
| V | None | Cached value or None if not found or expired. |
Set a cached value.
| Parameter | Type | Description |
|---|---|---|
| `key` | K | Cache key. |
| `value` | V | Value to cache. |
Check if key exists and is not expired.
| Parameter | Type | Description |
|---|---|---|
| `key` | K | Cache key. |
| Type | Description |
|---|---|
| bool | True if key exists and is valid. |
Delete a cached value.
| Parameter | Type | Description |
|---|---|---|
| `key` | K | Cache key. |
Clear all cached values.
Remove expired entries.
| Type | Description |
|---|---|
| int | Number of entries removed. |
InMemoryPersistedQueryStore
Section titled “InMemoryPersistedQueryStore”In-memory implementation of PersistedQueryStore.
Warning: Not suitable for production use with multiple instances. Use RedisPersistedQueryStore for production deployments.
Initialize the store.
| Parameter | Type | Description |
|---|---|---|
| `ttl_seconds` | int | None | Optional time-to-live for entries in seconds. |
Get a query by its hash.
Store a query with its hash.
Clear all stored queries.
IntrospectionConfig
Section titled “IntrospectionConfig”GraphQL introspection configuration.
Attributes:
enabled: Whether introspection is enabled. Defaults to True but the
executor automatically disables it in environments not listed in
allowed_environments.
allowed_environments: Set of environment names (matched against
LEX_ENV or the app environment) where introspection is
permitted. Defaults to {"development", "testing"}; production
is intentionally excluded.
IntrospectionHandler
Section titled “IntrospectionHandler”Handle GraphQL schema introspection.
Provides utilities for introspecting GraphQL schemas, extracting type information, and generating schema documentation.
Example
handler = IntrospectionHandler(schema)
# Get all typestypes = await handler.get_types()
# Get fields for a typefields = await handler.get_type_fields("User")Initialize the handler.
| Parameter | Type | Description |
|---|---|---|
| `schema` | Schema | Strawberry GraphQL schema. |
| `enabled` | bool | Whether introspection is enabled. |
Check if introspection is enabled.
Enable introspection.
Disable introspection.
Run introspection query.
| Parameter | Type | Description |
|---|---|---|
| `simplified` | bool | Use simplified query. |
| Type | Description |
|---|---|
| dict[str, Any] | Introspection result data. |
Get all types in the schema.
| Type | Description |
|---|---|
| list[dict[str, Any]] | List of type definitions. |
Get fields for a type.
| Parameter | Type | Description |
|---|---|---|
| `type_name` | str | Name of the type. |
| Type | Description |
|---|---|
| list[dict[str, Any]] | List of field definitions. |
Get the query type.
| Type | Description |
|---|---|
| dict[str, Any] | None | Query type definition or None. |
Get the mutation type.
| Type | Description |
|---|---|
| dict[str, Any] | None | Mutation type definition or None. |
Get the subscription type.
| Type | Description |
|---|---|
| dict[str, Any] | None | Subscription type definition or None. |
Clear the introspection cache.
Generate SDL (Schema Definition Language) from schema.
| Type | Description |
|---|---|
| str | Schema as SDL string. |
IsAdmin
Section titled “IsAdmin”Permission that requires admin role.
Check if user has admin role.
IsAuthenticated
Section titled “IsAuthenticated”Permission that requires user authentication.
Check if user is authenticated.
IsOwner
Section titled “IsOwner”Permission that requires ownership of the resource.
Check if user owns the resource.
IsOwnerOrAdmin
Section titled “IsOwnerOrAdmin”Permission that requires ownership or admin role.
Check if user owns the resource or is admin.
LoaderCache
Section titled “LoaderCache”Abstract base class for DataLoaderProtocol caches.
Implement this interface to provide custom caching behavior for DataLoaders.
Get a cached value.
| Parameter | Type | Description |
|---|---|---|
| `key` | K | Cache key. |
| Type | Description |
|---|---|
| V | None | Cached value or None. |
Set a cached value.
| Parameter | Type | Description |
|---|---|---|
| `key` | K | Cache key. |
| `value` | V | Value to cache. |
Check if key exists in cache.
| Parameter | Type | Description |
|---|---|---|
| `key` | K | Cache key. |
| Type | Description |
|---|---|
| bool | True if key exists. |
Delete a cached value.
| Parameter | Type | Description |
|---|---|---|
| `key` | K | Cache key. |
Clear all cached values.
MetricsCollectorProtocol
Section titled “MetricsCollectorProtocol”Collector for GraphQL metrics.
Collects and aggregates metrics from GraphQL operations. When a
MetricsRecorderProtocol is provided (resolved from the DI container) every
recorded query stat is forwarded to the kernel-level unified metrics
pipeline so GraphQL telemetry lands alongside infra metrics.
Example
from lexigram.contracts.observability.metrics import MetricsRecorderProtocol
collector = MetricsCollectorProtocol(recorder=recorder)collector.record(QueryStats(operation_name="GetUser", duration_ms=50.0))Initialize the collector.
| Parameter | Type | Description |
|---|---|---|
| `max_history` | int | Maximum number of stats to keep in the rolling history. |
| `recorder` | MetricsRecorderProtocol | None | Optional kernel MetricsRecorderProtocol for unified observability. |
def record(stats: QueryStats) -> None
Record query statistics and forward to the kernel MetricsRecorderProtocol.
| Parameter | Type | Description |
|---|---|---|
| `stats` | QueryStats | Query statistics. |
Record an error.
| Parameter | Type | Description |
|---|---|---|
| `error` | Exception | The exception. |
def get_metrics() -> GraphQLMetrics
Get current metrics.
| Type | Description |
|---|---|
| GraphQLMetrics | Current metrics. |
def get_recent_stats(limit: int = 100) -> list[QueryStats]
Get recent query statistics.
| Parameter | Type | Description |
|---|---|---|
| `limit` | int | Maximum number of stats to return. |
| Type | Description |
|---|---|
| list[QueryStats] | List of recent stats. |
Reset all metrics.
Async close hook for the collector (no-op).
Provides symmetry with other resources that expose async close so callers can await shutdown without conditional checks.
MetricsConfig
Section titled “MetricsConfig”Metrics collection configuration.
Attributes: enabled: Whether metrics are enabled. namespace: Metrics namespace/prefix. include_labels: Labels to include in metrics. histogram_buckets: Buckets for duration histograms.
MetricsExtension
Section titled “MetricsExtension”Strawberry extension for metrics collection.
Automatically collects metrics for all GraphQL operations.
Example
from lexigram.graphql.monitoring import MetricsExtension
schema = strawberry.Schema( query=Query, extensions=[MetricsExtension()],)Initialize the extension.
| Parameter | Type | Description |
|---|---|---|
| `collector` | MetricsCollectorProtocol | None | Metrics collector to use. |
Hook called during operation execution.
MutationResult
Section titled “MutationResult”Standard mutation result type.
Attributes: success: Whether the mutation succeeded. data: Result data if successful. errors: Error messages if failed.
NoOpCache
Section titled “NoOpCache”No-operation cache (disables caching).
Use this when you want to disable DataLoaderProtocol caching while keeping the batching behavior.
Always returns None.
Does nothing.
Always returns False.
Does nothing.
Does nothing.
OnErrorEvent
Section titled “OnErrorEvent”Emitted when a GraphQL operation encounters an unhandled exception.
This is fired for infrastructure-level errors (timeouts, executor crashes), not for user-facing field errors which are part of the normal GraphQL response.
OperationInfo
Section titled “OperationInfo”Information about a GraphQL operation.
OperationType
Section titled “OperationType”GraphQL operation types.
PageInfo
Section titled “PageInfo”Pagination information.
PagedResult
Section titled “PagedResult”Simple offset-based pagination result.
Attributes: items: List of items in the current page. total: Total number of items. page: Current page number (1-indexed). page_size: Number of items per page. has_next: Whether there are more pages. has_previous: Whether there are previous pages.
PaginationInput
Section titled “PaginationInput”Input for pagination parameters.
Attributes: page: Page number (1-indexed). page_size: Number of items per page.
PlaygroundConfig
Section titled “PlaygroundConfig”GraphQL Playground/GraphiQL configuration.
Attributes: enabled: Whether playground is enabled. path: Path to serve playground at. title: Title for the playground page.
QueryMetrics
Section titled “QueryMetrics”Metrics for a GraphQL query execution.
QueryStats
Section titled “QueryStats”Statistics for a single query execution.
Attributes: operation_name: Name of the operation. operation_type: Type (query, mutation, subscription). start_time: Execution start time. end_time: Execution end time. duration_ms: Execution duration in milliseconds. success: Whether execution succeeded. error_count: Number of errors.
RateLimitConfig
Section titled “RateLimitConfig”Configuration for rate limiting.
Attributes: enabled: Whether rate limiting is enabled. requests_per_minute: Number of allowed requests per minute. burst_limit: Maximum burst size.
RateLimitExtension
Section titled “RateLimitExtension”Enforce rate limiting on every GraphQL operation.
This extension delegates the actual limit check to the injected RateLimiter (resolved from the DI container by GraphQLProvider) and raises RateLimitError when the limit is exceeded.
Register it on the schema builder instead of wiring it into the executor
builder.add_extension( RateLimitExtension(rate_limiter=rate_limiter, max_requests=60))| Parameter | Type | Description |
|---|---|---|
| `rate_limiter` | Rate limiter implementation; when ``None`` the extension is a no-op (useful for local/test environments). | |
| `max_requests` | Request allowance per window. | |
| `window_seconds` | Window length in seconds. |
def __init__( *, rate_limiter: RateLimiter | None = None, max_requests: int = 60, window_seconds: int = 60 ) -> None
Check the rate limit before the GraphQL operation executes.
RateLimiter
Section titled “RateLimiter”Base class for rate limiters.
RedisPersistedQueryStore
Section titled “RedisPersistedQueryStore”Redis-backed implementation of PersistedQueryStore.
Suitable for production use with multiple application instances.
Initialize the store.
| Parameter | Type | Description |
|---|---|---|
| `redis_client` | Any | Redis client instance (aioRedis or redis-py async). |
| `key_prefix` | str | Prefix for Redis keys. |
| `ttl_seconds` | int | Time-to-live for entries in seconds. |
Get a query by its hash.
Store a query with its hash.
ResolverAdapter
Section titled “ResolverAdapter”Adapts a plain callable to the ResolverProtocol protocol.
Accepts any sync or async callable with the signature
(parent, args, context, info) -> Any and exposes it as a ResolverProtocol
via a resolve method. Sync callables are called directly; their
return value is awaited only when it happens to be a coroutine.
| Parameter | Type | Description |
|---|---|---|
| `func` | A sync or async callable that implements the resolver logic. The callable should accept up to four positional arguments: ``(parent, args, context, info)``. Arguments beyond what the callable declares are silently dropped so that short signatures (e.g. ``lambda parent, args: parent.id``) work transparently. |
Invoke the wrapped callable with the resolver arguments.
| Parameter | Type | Description |
|---|---|---|
| `parent` | Any | Parent (root) object for the field. |
| `args` | dict[str, Any] | Parsed field arguments from the GraphQL query. |
| `context` | Any | Shared execution context. |
| `info` | Any | GraphQL resolution info object. |
| Type | Description |
|---|---|
| Any | Resolved field value. |
ResolverInfo
Section titled “ResolverInfo”Context information passed to resolvers.
SchemaBuilderProtocol
Section titled “SchemaBuilderProtocol”Build GraphQL schemas with configuration.
Provides a fluent interface for constructing GraphQL schemas with proper configuration, extensions, and type registration.
Example
builder = SchemaBuilderProtocol()
schema = ( builder .query(Query) .mutation(Mutation) .subscription(Subscription) .add_extension(QueryLogger()) .build())def __init__(config: GraphQLConfig | None = None) -> None
Initialize the schema builder.
| Parameter | Type | Description |
|---|---|---|
| `config` | GraphQLConfig | None | GraphQL configuration. |
def query(query_type: type[Any]) -> SchemaBuilderProtocol
Set the query type.
| Parameter | Type | Description |
|---|---|---|
| `query_type` | type[Any] | The query type class. |
| Type | Description |
|---|---|
| SchemaBuilderProtocol | Self for chaining. |
def mutation(mutation_type: type[Any]) -> SchemaBuilderProtocol
Set the mutation type.
| Parameter | Type | Description |
|---|---|---|
| `mutation_type` | type[Any] | The mutation type class. |
| Type | Description |
|---|---|
| SchemaBuilderProtocol | Self for chaining. |
def subscription(subscription_type: type[Any]) -> SchemaBuilderProtocol
Set the subscription type.
| Parameter | Type | Description |
|---|---|---|
| `subscription_type` | type[Any] | The subscription type class. |
| Type | Description |
|---|---|
| SchemaBuilderProtocol | Self for chaining. |
def add_type(type_class: type[Any]) -> SchemaBuilderProtocol
Add an additional type to the schema.
| Parameter | Type | Description |
|---|---|---|
| `type_class` | type[Any] | The type class to add. |
| Type | Description |
|---|---|
| SchemaBuilderProtocol | Self for chaining. |
def add_types(*type_classes: type[Any]) -> SchemaBuilderProtocol
Add multiple types to the schema.
| Parameter | Type | Description |
|---|---|---|
| `type_classes` | type[Any] | Type classes to add. |
| Type | Description |
|---|---|
| SchemaBuilderProtocol | Self for chaining. |
def add_extension(extension: Any) -> SchemaBuilderProtocol
Add a schema extension.
| Parameter | Type | Description |
|---|---|---|
| `extension` | Any | The extension to add (kept as Any to avoid strict coupling to Strawberry's extension type in various environments). |
| Type | Description |
|---|---|
| SchemaBuilderProtocol | Self for chaining. |
def add_dataloader( name: str, factory: Any ) -> SchemaBuilderProtocol
Register a DataLoaderProtocol factory for per-request loader initialisation.
Stored factories are wired into ContextFactory by
GraphQLProvider during boot(),
so loaders are available inside resolvers via
context.get_dataloader(name).
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Unique loader name. |
| `factory` | Any | Callable ``(context) -> DataLoaderProtocol`` invoked per-request. |
| Type | Description |
|---|---|
| SchemaBuilderProtocol | Self for chaining. |
def add_directive(directive: Any) -> SchemaBuilderProtocol
Add a custom directive.
| Parameter | Type | Description |
|---|---|---|
| `directive` | Any | The directive to add. |
| Type | Description |
|---|---|
| SchemaBuilderProtocol | Self for chaining. |
def scalar_override( original: Any, override: Any ) -> SchemaBuilderProtocol
Override a scalar type.
| Parameter | Type | Description |
|---|---|---|
| `original` | Any | Original scalar type. |
| `override` | Any | Override scalar type. |
| Type | Description |
|---|---|
| SchemaBuilderProtocol | Self for chaining. |
Build the GraphQL schema.
| Type | Description |
|---|---|
| Schema | Configured Strawberry schema. |
| Exception | Description |
|---|---|
| ValueError | If no query type is set and no default is provided. |
property config() -> GraphQLConfig
Get the configuration.
SchemaBuiltEvent
Section titled “SchemaBuiltEvent”Emitted after the GraphQL schema is successfully built.
Consumers may inspect type counts for observability and diagnostics.
SchemaValidator
Section titled “SchemaValidator”Validate GraphQL schemas and queries.
Provides comprehensive validation of GraphQL queries against the schema, delegating depth enforcement to DepthLimitValidator and alias enforcement to AliasLimitValidator.
Example
validator = SchemaValidator(schema)result = validator.validate_query(query)
if not result.is_valid: for error in result.errors: logger.info("Validation error: %s", error)Initialize the validator.
| Parameter | Type | Description |
|---|---|---|
| `schema` | Any | GraphQL schema. |
| `max_depth` | int | Maximum query depth (delegated to DepthLimitValidator). |
| `max_aliases` | int | Maximum number of aliases (delegated to AliasLimitValidator). |
def validate_query( query: str, variables: dict[str, Any] | None = None ) -> ValidationResult
Validate a GraphQL query.
| Parameter | Type | Description |
|---|---|---|
| `query` | str | GraphQL query string. |
| `variables` | dict[str, Any] | None | Query variables. |
| Type | Description |
|---|---|
| ValidationResult | Validation result. |
SortInput
Section titled “SortInput”Input for sorting.
Attributes: field: Field to sort by. direction: Sort direction (ASC or DESC).
SubscriptionConfig
Section titled “SubscriptionConfig”WebSocket subscription configuration.
Attributes: enabled: Whether subscriptions are enabled. path: WebSocket path for subscriptions. protocol: WebSocket protocol to use. keepalive_interval: Keepalive interval in seconds. connection_timeout: Connection timeout in seconds.
SubscriptionInfo
Section titled “SubscriptionInfo”Information about an active subscription.
SubscriptionProtocol
Section titled “SubscriptionProtocol”WebSocket subscription protocols.
SubscriptionStartedEvent
Section titled “SubscriptionStartedEvent”Emitted when a GraphQL subscription is established.
Provides the subscription identifier and operation name for tracking and auditing long-lived connections.
TraceSpan
Section titled “TraceSpan”A span in the execution trace.
Attributes: name: Span name. start_time: Start timestamp. end_time: End timestamp. duration_ms: Duration in milliseconds. metadata: Additional span metadata. children: Child spans.
End the span and calculate duration.
def add_child(child: TraceSpan) -> None
Add a child span.
Convert to dictionary.
| Type | Description |
|---|---|
| dict[str, Any] | Dictionary representation. |
TracingConfig
Section titled “TracingConfig”Distributed tracing configuration.
Attributes: enabled: Whether tracing is enabled. service_name: Service name for tracing. trace_resolvers: Whether to trace individual resolvers. trace_dataloaders: Whether to trace DataLoaderProtocol batches. sample_rate: Sampling rate (0.0 to 1.0).
TracingExtension
Section titled “TracingExtension”Strawberry extension for query tracing.
Adds tracing information to query responses in Apollo tracing format.
Example
from lexigram.graphql.monitoring import TracingExtension
schema = strawberry.Schema( query=Query, extensions=[TracingExtension()],)Initialize the extension.
| Parameter | Type | Description |
|---|---|---|
| `include_in_response` | bool | Include tracing in response extensions. |
| `tracer` | TracerProtocol | None | Optional kernel TracerProtocol for unified distributed tracing. When provided, GraphQL operation and resolver spans are forwarded to the application-wide tracing pipeline so GraphQL telemetry is correlated with infra traces. |
Hook called during operation execution.
def resolve( _next: Callable[Ellipsis, Any], root: Any, info: Any, *args: Any, **kwargs: Any ) -> Any
Hook called during field resolution.
UnifiedRateLimiter
Section titled “UnifiedRateLimiter”Rate limiter that delegates to an injected web rate limiter.
Check if a request is allowed using the web rate limiter.
ValidationResult
Section titled “ValidationResult”Result of query validation.
Attributes: is_valid: Whether the query is valid. errors: List of validation errors. depth: Maximum query depth. field_count: Total number of fields. warnings: Non-fatal warnings.
Add a validation error.
Add a validation warning.
Functions
Section titled “Functions”compute_query_hash
Section titled “compute_query_hash”
Compute SHA256 hash of a GraphQL query.
| Parameter | Type | Description |
|---|---|---|
| `query` | str | The GraphQL query string. |
| Type | Description |
|---|---|
| str | Hex-encoded SHA256 hash. |
create_connection_type
Section titled “create_connection_type”
def create_connection_type( node_type: type[T], name: str | None = None ) -> type[Connection[T]]
Create a Connection type for a specific node type.
| Parameter | Type | Description |
|---|---|---|
| `node_type` | type[T] | The node type for the connection. |
| `name` | str | None | Optional name prefix for the connection type. |
| Type | Description |
|---|---|
| type[Connection[T]] | A Connection type class. |
create_depth_limit
Section titled “create_depth_limit”
def create_depth_limit( max_depth: int = 10, ignore_introspection: bool = True ) -> DepthLimitExtension
Create a depth limit extension (convenience function).
| Parameter | Type | Description |
|---|---|---|
| `max_depth` | int | Maximum allowed depth. |
| `ignore_introspection` | bool | Skip introspection queries. |
| Type | Description |
|---|---|
| DepthLimitExtension | Configured extension. |
Example
schema = strawberry.Schema( query=Query, extensions=[create_depth_limit(5)],)create_loader
Section titled “create_loader”
def create_loader( batch_fn: Callable[[list[K]], Awaitable[list[V | None]]], batch_size: int = 100, cache_enabled: bool = True ) -> DataLoaderProtocol[K, V]
Create a DataLoaderProtocol (convenience function).
| Parameter | Type | Description |
|---|---|---|
| `batch_fn` | Callable[[list[K]], Awaitable[list[V | None]]] | Batch load function. |
| `batch_size` | int | Maximum batch size. |
| `cache_enabled` | bool | Whether to enable caching. |
| Type | Description |
|---|---|
| DataLoaderProtocol[K, V] | Configured DataLoaderProtocol. |
Example
user_loader = create_loader( batch_load_users, batch_size=50,)
user = await user_loader.load("123")create_schema
Section titled “create_schema”
def create_schema( query: type[Any], mutation: type[Any] | None = None, subscription: type[Any] | None = None, types: list[type[Any]] | None = None, extensions: list[Any] | None = None, config: GraphQLConfig | None = None ) -> Schema
Create a GraphQL schema (convenience function).
| Parameter | Type | Description |
|---|---|---|
| `query` | type[Any] | Query type class. |
| `mutation` | type[Any] | None | Optional mutation type class. |
| `subscription` | type[Any] | None | Optional subscription type class. |
| `types` | list[type[Any]] | None | Additional type classes. |
| `extensions` | list[Any] | None | Schema extensions. |
| `config` | GraphQLConfig | None | GraphQL configuration. |
| Type | Description |
|---|---|
| Schema | Configured Strawberry schema. |
Example
schema = create_schema( query=Query, mutation=Mutation, config=GraphQLConfig(depth_limit=5),)decode_cursor
Section titled “decode_cursor”
Decode a base64 cursor to an offset.
| Parameter | Type | Description |
|---|---|---|
| `cursor` | str | The cursor string to decode. |
| Type | Description |
|---|---|
| int | The decoded offset. |
| Exception | Description |
|---|---|
| ValueError | If the cursor is invalid. |
decode_cursor_to_id
Section titled “decode_cursor_to_id”
Decode a cursor to an item ID.
| Parameter | Type | Description |
|---|---|---|
| `cursor` | str | The cursor string to decode. |
| Type | Description |
|---|---|
| str | The decoded item ID. |
| Exception | Description |
|---|---|
| ValueError | If the cursor is invalid. |
encode_cursor
Section titled “encode_cursor”
Encode an offset as a base64 cursor.
| Parameter | Type | Description |
|---|---|---|
| `offset` | int | The offset to encode. |
| Type | Description |
|---|---|
| str | Base64-encoded cursor string. |
encode_cursor_from_id
Section titled “encode_cursor_from_id”
Encode an item ID as an opaque cursor.
| Parameter | Type | Description |
|---|---|---|
| `item_id` | str | The item ID to encode. |
| Type | Description |
|---|---|
| str | Base64-encoded cursor string. |
execute_query
Section titled “execute_query”
async def execute_query( schema: StrawberrySchema, query: str, variables: dict[str, Any] | None = None, operation_name: str | None = None, context: GraphQLContext | None = None ) -> GraphQLResponse[Any]
Execute a GraphQL query (convenience function).
If you need to build a context from a plain dictionary, use
ContextFactory.from_dict() before calling this function.
| Parameter | Type | Description |
|---|---|---|
| `schema` | StrawberrySchema | Strawberry GraphQL schema. |
| `query` | str | GraphQL query string. |
| `variables` | dict[str, Any] | None | Query variables. |
| `operation_name` | str | None | Operation name. |
| `context` | GraphQLContext | None | GraphQL context. |
| Type | Description |
|---|---|
| GraphQLResponse[Any] | GraphQL response. |
def field( name: str | None = None, description: str | None = None, deprecation_reason: str | None = None, default: Any = strawberry.UNSET, default_factory: Callable[[], Any] | None = None, permission_classes: list[Any] | None = None ) -> Any
Define a GraphQL field.
This is a wrapper around Strawberry’s field function with additional Lexigram-specific functionality.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | None | Optional field name. |
| `description` | str | None | Field description. |
| `deprecation_reason` | str | None | Deprecation reason if deprecated. |
| `default` | Any | Default value. |
| `default_factory` | Callable[[], Any] | None | Factory for default value. |
| `permission_classes` | list[Any] | None | Permission classes for authorization. |
| Type | Description |
|---|---|
| Any | Strawberry field. |
Example
@strawberry.typeclass User: id: str name: str = field(description="User's full name") email: str = field(description="User's email address")get_context
Section titled “get_context”
def get_context(info: Info) -> GraphQLContext
Get the GraphQL context from resolver info.
| Parameter | Type | Description |
|---|---|---|
| `info` | Info | Strawberry resolver info. |
| Type | Description |
|---|---|
| GraphQLContext | GraphQL context. |
Example
@strawberry.typeclass Query: @strawberry.field async def me(self, info: Info) -> User: context = get_context(info) return context.userget_introspection_query
Section titled “get_introspection_query”
Get the GraphQL introspection query.
| Parameter | Type | Description |
|---|---|---|
| `simplified` | bool | If True, return simplified query. |
| Type | Description |
|---|---|
| str | Introspection query string. |
get_metrics_collector
Section titled “get_metrics_collector”
Get the metrics collector instance.
log_resolver
Section titled “log_resolver”
Wrap an async GraphQL resolver with structured entry/exit/error logging.
Emits debug-level log events on entry and exit, and an error-level event when an exception propagates out of the resolver. The exception is always re-raised — this decorator never swallows errors.
| Parameter | Type | Description |
|---|---|---|
| `fn` | F | The async resolver function to wrap. |
| Type | Description |
|---|---|
| F | Wrapped resolver with structured logging applied. |
Example
@strawberry.typeclass Mutation: @log_resolver async def create_user(self, info: Info, input: CreateUserInput) -> User: return await service.create(input)mutation
Section titled “mutation”
def mutation( name: str | None = None, description: str | None = None, deprecation_reason: str | None = None, permission_classes: list[Any] | None = None ) -> Callable[[Callable[P, T]], Callable[P, Any]]
Decorator for marking a method as a GraphQL mutation.
This is a wrapper around Strawberry’s mutation decorator with additional Lexigram-specific functionality.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | None | Optional field name (defaults to function name). |
| `description` | str | None | Field description for documentation. |
| `deprecation_reason` | str | None | If set, marks the field as deprecated. |
| `permission_classes` | list[Any] | None | List of permission classes for authorization. |
| Type | Description |
|---|---|
| Callable[[Callable[P, T]], Callable[P, Any]] | Decorated function. |
Example
@strawberry.typeclass Mutation: @mutation(description="Create a new user") async def create_user( self, info: Info, input: CreateUserInput ) -> User: return await create_user(input)
def query( name: str | None = None, description: str | None = None, deprecation_reason: str | None = None, permission_classes: list[Any] | None = None ) -> Callable[[Callable[P, T]], Callable[P, Any]]
Decorator for marking a method as a GraphQL query.
This is a wrapper around Strawberry’s field decorator with additional Lexigram-specific functionality.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | None | Optional field name (defaults to function name). |
| `description` | str | None | Field description for documentation. |
| `deprecation_reason` | str | None | If set, marks the field as deprecated. |
| `permission_classes` | list[Any] | None | List of permission classes for authorization. |
| Type | Description |
|---|---|
| Callable[[Callable[P, T]], Callable[P, Any]] | Decorated function. |
Example
@strawberry.typeclass Query: @query(description="Get user by ID") async def user(self, info: Info, id: str) -> User: return await get_user(id)resolver
Section titled “resolver”
def resolver( name: str | None = None, description: str | None = None ) -> Callable[[Callable[P, T]], Callable[P, Any]]
Decorator for field resolvers.
Use this to define a resolver function that can be used as a field resolver in a GraphQL type.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | None | Optional resolver name. |
| `description` | str | None | ResolverProtocol description. |
| Type | Description |
|---|---|
| Callable[[Callable[P, T]], Callable[P, Any]] | Decorated resolver function. |
Example
@resolver(description="Resolve user's full name")async def resolve_full_name( root: User, info: Info) -> str: return f"{root.first_name} {root.last_name}"
@strawberry.typeclass User: first_name: str last_name: str full_name: str = strawberry.field(resolver=resolve_full_name)retry_resolver
Section titled “retry_resolver”
def retry_resolver( max_retries: int = 3, *, delay: float = 0.1, exceptions: tuple[type[Exception], Ellipsis] = (Exception,) ) -> Callable[[F], F]
Wrap an async GraphQL resolver with automatic retry logic.
Retries the decorated resolver up to max_retries times when any of the
specified exceptions are raised. Uses exponential back-off between
attempts: delay * 2 ** attempt seconds.
| Parameter | Type | Description |
|---|---|---|
| `max_retries` | int | Maximum number of attempts before re-raising the last exception. Must be at least 1. |
| `delay` | float | Base delay in seconds between retries. Doubles on each attempt. |
| `exceptions` | tuple[type[Exception], Ellipsis] | Tuple of exception types that trigger a retry. Defaults to ``(Exception,)`` — any exception retries. |
Example
@strawberry.typeclass Query: @retry_resolver(max_retries=3, delay=0.2, exceptions=(TimeoutError,)) async def user(self, info: Info, id: str) -> User: return await fetch_user(id)subscription
Section titled “subscription”
def subscription( name: str | None = None, description: str | None = None, deprecation_reason: str | None = None, permission_classes: list[Any] | None = None ) -> Callable[[Callable[P, T]], Callable[P, Any]]
Decorator for marking a method as a GraphQL subscription.
This is a wrapper around Strawberry’s subscription decorator with additional Lexigram-specific functionality.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | None | Optional field name (defaults to function name). |
| `description` | str | None | Field description for documentation. |
| `deprecation_reason` | str | None | If set, marks the field as deprecated. |
| `permission_classes` | list[Any] | None | List of permission classes for authorization. |
| Type | Description |
|---|---|
| Callable[[Callable[P, T]], Callable[P, Any]] | Decorated function. |
Example
@strawberry.typeclass Subscription: @subscription(description="Subscribe to messages") async def messages( self, info: Info, room_id: str ) -> AsyncGenerator[Message, None]: async for msg in message_stream(room_id): yield msgtrace_resolver
Section titled “trace_resolver”
Decorator for tracing resolver execution.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | None | Optional span name. |
| Type | Description |
|---|---|
| Callable[[Callable[P, T]], Callable[P, T]] | Decorator function. |
Example
@strawberry.typeclass Query: @trace_resolver("fetch_user") @strawberry.field async def user(self, info: Info, id: str) -> User: return await get_user(id)union_type
Section titled “union_type”
Create a GraphQL union type.
| Parameter | Type | Description |
|---|---|---|
| `types` | Any | Types to include in the union. |
| `name` | str | None | Optional name for the union. |
| Type | Description |
|---|---|
| Any | Union type annotation. |
Example
SearchResult = union_type(User, Post, Comment, name="SearchResult")
@strawberry.typeclass Query: @strawberry.field def search(self, query: str) -> list[SearchResult]: ...validate_query
Section titled “validate_query”
def validate_query( schema: Any, query: str, variables: dict[str, Any] | None = None, max_depth: int = 10 ) -> ValidationResult
Validate a GraphQL query (convenience function).
| Parameter | Type | Description |
|---|---|---|
| `schema` | Any | GraphQL schema. |
| `query` | str | GraphQL query string. |
| `variables` | dict[str, Any] | None | Query variables. |
| `max_depth` | int | Maximum allowed depth. |
| Type | Description |
|---|---|
| ValidationResult | Validation result. |
Exceptions
Section titled “Exceptions”AuthenticationError
Section titled “AuthenticationError”Raised when authentication is required but missing.
Also satisfies lexigram.contracts.exceptions.AuthenticationError so
middleware that catches the contracts type will catch this as well.
AuthorizationError
Section titled “AuthorizationError”Raised when user is authenticated but lacks permissions.
Also satisfies lexigram.contracts.exceptions.AuthorizationError so
middleware that catches the contracts type will catch this as well.
ForbiddenError
Section titled “ForbiddenError”Raised when access is forbidden.
GraphQLConnectionError
Section titled “GraphQLConnectionError”Raised when a network connection error occurs during GraphQL execution.
GraphQLError
Section titled “GraphQLError”Base exception for all GraphQL errors.
def __init__( message: str, *, code: GraphQLErrorCode | None = None, **kwargs: Any ) -> None
InputGraphQLError
Section titled “InputGraphQLError”Raised for invalid user input.
NotFoundError
Section titled “NotFoundError”Raised when a requested resource is not found.
ParseError
Section titled “ParseError”Raised when query parsing fails.
QueryTooComplexError
Section titled “QueryTooComplexError”Raised when query exceeds complexity limit.
QueryTooDeepError
Section titled “QueryTooDeepError”Raised when a GraphQL query exceeds the maximum depth.
RateLimitError
Section titled “RateLimitError”Raised when rate limit is exceeded.
ResolverError
Section titled “ResolverError”Raised when a resolver fails.
SubscriptionError
Section titled “SubscriptionError”Raised for subscription-related errors.