py_gql#

py_gql

py_gql is a pure python implementation of the GraphQL query language for Python 3.5+.

The main py_gql package provides the minimum required to build GraphQL schemas and execute queries against them while the relevant submodules allow you implement custom behaviors and runtimes.

py_gql.graphql(schema, document, *, variables=None, operation_name=None, root=None, context=None, validators=None, middlewares=None, instrumentation=None)[source]#

Execute a GraphQL query on the AsyncIO runtime.

This is a wrapper around process_graphql_query() enforcing usage of AsyncIORuntime.

Warning

Blocking (non async) resolvers will block the current thread.

Return type:GraphQLResult
py_gql.graphql_blocking(schema, document, *, variables=None, operation_name=None, root=None, context=None, validators=None, middlewares=None, instrumentation=None)[source]#

Execute a GraphQL query in the current thread.

Wrapper around process_graphql_query() enforcing usage of blocking resolvers. This uses an optimized Executor subclass.

Return type:GraphQLResult
py_gql.process_graphql_query(schema, document, *, variables=None, operation_name=None, root=None, context=None, validators=None, middlewares=None, instrumentation=None, disable_introspection=False, runtime=None, executor_cls=<class 'py_gql.execution.executor.Executor'>)[source]#

Execute a GraphQL query.

This is the main GraphQL entrypoint encapsulating query processing from start to finish including parsing, validation, variable coercion and execution.

Parameters:
  • schema (Schema) – Schema to execute the query against.
  • document (Union[str, Document]) – The query document.
  • variables (Optional[Mapping[str, Any]]) – Raw, JSON decoded variables parsed from the request.
  • operation_name (Optional[str]) – Operation to execute If specified, the operation with the given name will be executed. If not, this executes the single operation without disambiguation.
  • root (Optional[Any]) – Root resolution value passed to the top-level resolver.
  • context (Optional[Any]) – Custom application-specific execution context. Use this to pass in anything your resolvers require like database connection, user information, etc. Limits on the type(s) used here will depend on your own resolver and the runtime implementations used. Most thread safe data-structures should work with built in runtimes.
  • validators (Optional[Sequence[Callable[[Schema, Document, Optional[Dict[str, Any]]], Iterable[ValidationError]]]]) – Custom validators. Setting this will replace the defaults so if you just want to add some rules, append to py_gql.validation.SPECIFIED_RULES.
  • middlewares (Optional[Sequence[Callable[…, Any]]]) – List of middleware functions. Middlewares are used to wrap the resolution of all fields with common logic, they are good candidates for logging, authentication, and execution guards.
  • instrumentation (Optional[Instrumentation]) – Instrumentation instance. Use MultiInstrumentation to compose multiple instances together.
  • disable_introspection (bool) – Use this to prevent schema introspection. This can be useful when you want to hide your full schema while keeping your API available. Note that this deviates from the GraphQL specification and will likely break some clients (such as GraphiQL) so use this with caution.
  • runtime (Optional[Runtime]) – Runtime against which to execute field resolvers (defaults to ~py_gql.execution.runtime.BlockingRuntime()).
  • executor_cls (Type[Executor]) – Executor class to use. The executor class defines the implementation of the GraphQL resolution algorithm. This must be a subclass of py_gql.execution.Executor.
Return type:

Any

Returns:

Execution result.

The returned value will depend on the runtime argument. Custom implementations usually return a type wrapping the GraphQLResult object such as Awaitable when using AsyncIORuntime.

class py_gql.GraphQLResult(data=<object object>, errors=None)[source]#

Operation response.

This wrapper encodes the behavior described in the Response part of the specification.

Parameters:
  • data (Optional[Dict[str, Any]]) – The data part of the response.
  • errors (Optional[Sequence[GraphQLResponseError]]) – The errors part of the response. All errors will be included in the response using to_dict().
add_extension(ext)[source]#

Add an extensions to the result.

Parameters:ext – Extension instance
Raises:ValueError – Extension with the same name has already been added
json(**kw)[source]#

Encode response as JSON using the standard lib json module.

Parameters:**kw – Keyword args passed to to json.dumps
Returns:JSON serialized response.
Return type:str
response()[source]#

Generate an ordered response dict.

Return type:Dict[str, Any]
class py_gql.ResolveInfo(field_definition, path, parent_type, nodes, runtime, context)[source]#

Expose information about the field currently being resolved.

This is the 3rd positional argument provided to resolver functions and is constructed internally during query execution.

Warning

This class assumes that the document and schema have been validated for execution and may break unexectedly if used outside of such a context.

field_definition#

Root field being resolved.

Type:Field
fragments#

Document fragments.

Return type:Dict[str, FragmentDefinition]
get_all_directive_arguments(name)[source]#

Extract arguments for a given directive on the current field.

This has the same semantics as py_gql.utilities.all_directive_arguments.

Parameters:name (str) – The name of the directive to extract.
Return type:List[Dict[str, Any]]
Returns:List of directive arguments in order of occurrence.
get_directive_arguments(name)[source]#

Extract arguments for a given directive on the current field.

This has the same semantics as py_gql.utilities.directive_arguments.

Parameters:name (str) – The name of the directive to extract.
Return type:Optional[Dict[str, Any]]
Returns:None if the directive is not present on the current field and a dictionary of coerced arguments otherwise.
nodes#

AST nodes extracted from the document.

Type:Field
parent_type#

Type from which the field is being resolved.

Type:ObjectType
path#

Current traversal path through the query.

Type:ResponsePath
runtime#

Current runtime.

Type:Runtime
schema#

Current schema.

Return type:Schema
selected_fields(*, maxdepth=1, pattern=None)[source]#

Extract the list of fields selected by the field currently being resolved.

Refer to selected_fields() for documentation.

Return type:List[str]
variables#

Coerced variables.

Return type:Dict[str, Any]
py_gql.build_schema(document, *, ignore_extensions=False, additional_types=None, schema_directives=None)[source]#

Build an executable schema from a GraphQL document.

This includes:

  • Generating types from their definitions
  • Applying schema and type extensions
  • Applying schema directives
Parameters:
  • document (Union[Document, str]) – SDL document
  • ignore_extensions (bool) – Whether to apply schema and type extensions or not.
  • additional_types (Optional[List[NamedType]]) – User supplied list of types Use this to specify some custom implementation for scalar, enums, etc. - In case of object types, interfaces, etc. the supplied type will override the extracted type without checking for compatibility. - Extension will be applied to these types. As a result, the resulting types may not be the same objects that were provided, so users should not rely on type identity.
  • schema_directives (Optional[Sequence[~TSchemaDirective]]) –

    Schema directive classes. Members must be subclasses of py_gql.schema.SchemaDirective

    Note

    Specified directives such as @deperecated do not need to be specified this way and are always processed internally to ensure compliance with the specification.

Return type:

Schema

Returns:

Executable schema

Raises: