API reference#

Root of the quiz API.

The entire public API is available at root level:

>>> import quiz
>>> quiz.Schema, quiz.execute, quiz.SelectionError, ...

quiz.build#

Main module for constructing graphQL queries

class quiz.build.SelectionSet(*selections)[source]#

Bases: Iterable[Selection], Sized

Sequence of selections

Parameters:

*selections (Selection) – Items in the selection set.

Notes

  • Instances are immutable.

  • Extending selection sets is possible through special methods (__getattr__, __call__, __getitem__)

__getattr__(fieldname)[source]#

Add a new field to the selection set.

Parameters:

fieldname (str) – The name of the field to add.

Returns:

A selection set with the new field added to the end.

Return type:

SelectionSet

Example

This functionality can be used to quickly create a sequence of fields:

>>> _ = SelectionSet()
>>> str(
...     _
...     .foo
...     .bar
...     .bing
... )
{
  foo
  bar
  bing
}
__getitem__(selections)[source]#

Add a sub-selection to the last field in the selection set

Parameters:

selections (SelectionSet) – The selection set to nest

Example

>>> _ = SelectionSet()
>>> str(
...     _
...     .foo
...     .bar[
...         _
...         .qux
...         .bing
...     ]
...     .other_field
... )
{
  foo
  bar {
    qux
    bing
  }
  other_field
}
Returns:

A selection set with selections added to the last field.

Return type:

SelectionSet

Raises:

utils.Empty – In case the selection set is empty

__call__(**kwargs)[source]#

The selection set may be called in two distinct ways:

  1. With keyword arguments **kwargs. These will be added as arguments to the last field in the selection set.

  2. With a single alias argument. This has the affect of adding an alias to the next field in the selection set.

Parameters:
  • alias (str, optional) –

    If given, the next field in the selection set will get this alias.

    Example

    >>> _ = SelectionSet()
    >>> str(
    ...     _
    ...     .foo
    ...     ('my_alias').bla
    ...     .other_field
    ... )
    {
       foo
       my_alias: bla
       other_field
    }
    

    Note

    The alias can only be specified as a positional argument, and may not be combined with **kwargs.

  • **kwargs

    Adds arguments to the previous field in the chain

    Example

    >>> _ = SelectionSet()
    >>> str(
    ...     _
    ...     .foo
    ...     .bla(a=4, b='qux')
    ...     .other_field
    ... )
    {
      foo
      bla(a: 4, b: "qux")
      other_field
    }
    

    Note

    Each field argument must be a keyword argument.

Returns:

The new selection set

Return type:

SelectionSet

Raises:

utils.Empty – In case field arguments are given, but the selection set is empty

__iter__()[source]#

Iterate over the selection set contents

Returns:

An iterator over selections

Return type:

Iterator[Selection]

__len__()[source]#

Number of items in the selection set

Returns:

The number of items in the selection set

Return type:

int

__str__()[source]#

The selection set as raw graphQL

quiz.build.Selection#

Field or inline fragment

alias of Union[Field, InlineFragment]

class quiz.build.Field(name, kwargs={}, selection_set=<SelectionSet>, alias=None)[source]#

Bases: ValueObject

property alias#

Field alias

property kwargs#

Given arguments

property name#

Field name

property selection_set#

Selection of subfields

class quiz.build.InlineFragment(on, selection_set)[source]#

Bases: ValueObject

property on#

Type of the fragment

property selection_set#

Subfields of the fragment

class quiz.build.Raw(content)[source]#

Bases: ValueObject

property content#

The raw GraphQL content

class quiz.build.Query(cls, selections)[source]#

Bases: ValueObject

__str__()[source]#

Return str(self).

property cls#

The query class

property selections#

Fields selection

quiz.build.SELECTOR = <SelectionSet> #

An empty, extendable SelectionSet

quiz.build.escape(txt)[source]#

Escape a string according to GraphQL specification

Parameters:

txt (str) – The string to escape

Returns:

the escaped string

Return type:

str

quiz.types#

Components for typed GraphQL interactions

class quiz.types.Enum(value)[source]#

Bases: Enum

An enumeration.

class quiz.types.GenericScalar[source]#

Bases: Scalar

A generic scalar, accepting any primitive type

class quiz.types.Scalar[source]#

Bases: object

Base class for scalars

__gql_dump__()[source]#

Serialize the scalar to a GraphQL primitive value

classmethod __gql_load__(data)[source]#

Load a scalar instance from GraphQL

class quiz.types.Interface[source]#

Bases: HasFields

metaclass for interfaces

class quiz.types.Object(**kwargs)[source]#

Bases: Namespace

a graphQL object

class quiz.types.InputValue(name, desc, type)#

Bases: tuple

desc: str#

Alias for field number 1

name: str#

Alias for field number 0

type: type#

Alias for field number 2

quiz.types.validate(cls, selection_set)[source]#

Validate a selection set against a type

Parameters:
  • cls (type) – The class to validate against, an Object or Interface

  • selection_set (SelectionSet) – The selection set to validate

Returns:

The validated selection set

Return type:

SelectionSet

Raises:

SelectionError – If the selection set is not valid

exception quiz.types.ValidationError[source]#

Bases: Exception

base class for validation errors

exception quiz.types.SelectionError(on, path, error)[source]#

Bases: ValueObject, ValidationError

__str__()[source]#

Return str(self).

property error#

Original error

property on#

Type on which the error occurred

property path#

Path at which the error occurred

exception quiz.types.NoSuchField[source]#

Bases: ValueObject, ValidationError

__str__()[source]#

Return str(self).

exception quiz.types.NoSuchArgument(name)[source]#

Bases: ValueObject, ValidationError

__str__()[source]#

Return str(self).

property name#

(Invalid) argument name

exception quiz.types.SelectionsNotSupported[source]#

Bases: ValueObject, ValidationError

__str__()[source]#

Return str(self).

exception quiz.types.InvalidArgumentType(name, value)[source]#

Bases: ValueObject, ValidationError

__str__()[source]#

Return str(self).

property name#

Argument name

property value#

(Invalid) value

exception quiz.types.MissingArgument(name)[source]#

Bases: ValueObject, ValidationError

__str__()[source]#

Return str(self).

property name#

Missing argument name

exception quiz.types.NoValueForField[source]#

Bases: AttributeError

Indicates a value cannot be retrieved for the field

quiz.types.load(cls, selection_set, response)[source]#

Load a response for a selection set

Parameters:
  • cls (Type[T]) – The class to load against, an Object or Interface

  • selection_set (SelectionSet) – The selection set to validate

  • response (t.Mapping[str, JSON]) – The JSON response data

Returns:

An instance of cls

Return type:

T

quiz.execution#

Components for executing GraphQL operations

quiz.execution.execute(obj, url, **kwargs)[source]#

Execute a GraphQL executable

Parameters:
  • obj (Executable) – The object to execute. This may be a raw string or a query

  • url (str) – The URL of the target endpoint

  • **kwargsauth and/or client, passed to snug.query.execute().

Returns:

In case of a raw string, a raw result. Otherwise, an instance of the schema’s type queried for.

Return type:

RawResult (a dict) or the schema’s return type

Raises:
  • ErrorResponse – If errors are present in the response

  • HTTPError – If the response has a non 2xx response code

quiz.execution.execute_async(obj, url, **kwargs)[source]#

Execute a GraphQL executable asynchronously

Parameters:
  • obj (Executable) – The object to execute. This may be a raw string or a query

  • url (str) – The URL of the target endpoint

  • **kwargsauth and/or client, passed to snug.query.execute_async().

Returns:

In case of a raw string, a raw result. Otherwise, an instance of the schema’s type queried for.

Return type:

RawResult (a dict) or the schema’s return type

Raises:
  • ErrorResponse – If errors are present in the response

  • HTTPError – If the response has a non 2xx response code

quiz.execution.executor(**kwargs)[source]#

Create a version of execute() with bound arguments. Equivalent to partial(execute, **kwargs).

Parameters:

**kwargsurl, auth, and/or client, passed to execute()

Returns:

A callable to execute GraphQL executables

Return type:

Callable[[Executable], JSON]

Example

>>> execute = executor(url='https://api.github.com/graphql',
...                    auth=('me', 'password'))
>>> result = execute('''
...   {
...     repository(owner: "octocat" name: "Hello-World") {
...       description
...     }
...   }
... ''', client=requests.Session())
quiz.execution.async_executor(**kwargs)[source]#

Create a version of execute_async() with bound arguments. Equivalent to partial(execute_async, **kwargs).

Parameters:

**kwargsurl, auth, and/or client, passed to execute_async()

Returns:

A callable to asynchronously execute GraphQL executables

Return type:

Callable[[Executable], Awaitable[JSON]]

Example

>>> execute = async_executor(url='https://api.github.com/graphql',
...                          auth=('me', 'password'))
>>> result = await execute('''
...   {
...     repository(owner: "octocat" name: "Hello-World") {
...       description
...     }
...   }
... ''')
quiz.execution.Executable#

Anything which can be executed as a GraphQL operation

alias of Union[str, Query]

exception quiz.execution.ErrorResponse(data, errors)[source]#

A response containing errors

property data#

Data returned in the response

property errors#

Errors returned in the response

exception quiz.execution.HTTPError(response, request)[source]#

Indicates a response with a non 2xx status code

property request#

The original request

property response#

The response object

class quiz.execution.RawResult(items, meta)[source]#

Dictionary as result of a raw query.

Contains HTTP metadata in its __metadata__ attribute.

class quiz.execution.QueryMetadata(response, request)[source]#

HTTP metadata for query

property request#

The original request

property response#

The response object

quiz.schema#

Functionality relating to the raw GraphQL schema

class quiz.schema.Schema(classes, query_type, mutation_type, subscription_type, module, raw)[source]#

A GraphQL schema.

Use from_path(), from_url(), or from_raw() to instantiate.

populate_module()[source]#

Populate the schema’s module with the schema’s classes

Note

The schema’s module must be set (i.e. not None)

Raises:

RuntimeError – If the schema module is not set

property query#

Creator for a query operation

Example

>>> from quiz import SELECTOR as _
>>> str(schema.query[
...     _
...     .field1
...     .foo
... ])
query {
  field1
  foo
}
classmethod from_path(path, module=None, scalars=())[source]#

Create a Schema from a JSON at a path

Parameters:
  • path (str or PathLike) – The path to the raw schema JSON file.

  • module (Optional[str], optional) – The name of the module to use when creating the schema’s classes.

  • scalars (Iterable[Type[Scalar]]) – Scalar classes to use in the schema. Scalars in the schema, but not in this sequence, will be defined as GenericScalar subclasses.

Returns:

The generated schema

Return type:

Schema

Raises:

IOError – If the file at given path cannot be read

to_path(path)[source]#

Dump the schema as JSON to a path

Parameters:

path (str or PathLike) – The path to write the raw schema to

classmethod from_raw(raw_schema, module=None, scalars=())[source]#

Create a Schema from a raw JSON schema

Parameters:
Returns:

The schema constructed from raw data

Return type:

Schema

classmethod from_url(url, scalars=(), module=None, **kwargs)[source]#

Build a GraphQL schema by introspecting an API

Parameters:
  • url (str) – URL of the target GraphQL API

  • scalars (Iterable[Type[Scalar]]) – Scalar classes to use in the schema. Scalars in the schema, but not in this sequence, will be defined as GenericScalar subclasses.

  • module (Optional[str], optional) – The module name to set on the generated classes

  • **kwargsauth or client, passed to execute().

Returns:

The generated schema

Return type:

Schema

Raises:

ErrorResponse – If there are errors in the response data

property classes#

Mapping of classes in the schema

property module#

The module to which the classes are namespaced

property mutation_type#

The mutation type of the schema

property query_type#

The query type of the schema

property raw#

The raw schema (JSON). To be deprecated

property subscription_type#

The subscription type of the schema

quiz.schema.INTROSPECTION_QUERY = '\n{\n  __schema {\n    queryType { name }\n    mutationType { name }\n    subscriptionType { name }\n    types {\n      ...FullType\n    }\n  }\n}\n\nfragment FullType on __Type {\n  kind\n  name\n  description\n  fields(includeDeprecated: true) {\n    name\n    description\n    args {\n      ...InputValue\n    }\n    type {\n      ...TypeRef\n    }\n    isDeprecated\n    deprecationReason\n  }\n  inputFields {\n    ...InputValue\n  }\n  interfaces {\n    ...TypeRef\n  }\n  enumValues(includeDeprecated: true) {\n    name\n    description\n    isDeprecated\n    deprecationReason\n  }\n  possibleTypes {\n    ...TypeRef\n  }\n}\n\nfragment InputValue on __InputValue {\n  name\n  description\n  type { ...TypeRef }\n  defaultValue\n}\n\nfragment TypeRef on __Type {\n  kind\n  name\n  ofType {\n    kind\n    name\n    ofType {\n      kind\n      name\n      ofType {\n        kind\n        name\n      }\n    }\n  }\n}\n'#

Query to retrieve the raw schema

quiz.utils#

Common utilities and boilerplate

exception quiz.utils.Empty[source]#

indicates a given list is unexpectedly empty