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:
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:
- Raises:
utils.Empty – In case the selection set is empty
- __call__(**kwargs)[source]#
The selection set may be called in two distinct ways:
With keyword arguments
**kwargs
. These will be added as arguments to the last field in the selection set.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:
- 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]
- 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.Query(cls, selections)[source]#
Bases:
ValueObject
- property cls#
The query class
- property selections#
Fields selection
- quiz.build.SELECTOR = <SelectionSet> #
An empty, extendable
SelectionSet
quiz.types
#
Components for typed GraphQL interactions
- class quiz.types.GenericScalar[source]#
Bases:
Scalar
A generic scalar, accepting any primitive type
- quiz.types.validate(cls, selection_set)[source]#
Validate a selection set against a type
- Parameters:
cls (type) – The class to validate against, an
Object
orInterface
selection_set (SelectionSet) – The selection set to validate
- Returns:
The validated selection set
- Return type:
- Raises:
SelectionError – If the selection set is not valid
- exception quiz.types.SelectionError(on, path, error)[source]#
Bases:
ValueObject
,ValidationError
- 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
- exception quiz.types.NoSuchArgument(name)[source]#
Bases:
ValueObject
,ValidationError
- property name#
(Invalid) argument name
- exception quiz.types.SelectionsNotSupported[source]#
Bases:
ValueObject
,ValidationError
- exception quiz.types.InvalidArgumentType(name, value)[source]#
Bases:
ValueObject
,ValidationError
- property name#
Argument name
- property value#
(Invalid) value
- exception quiz.types.MissingArgument(name)[source]#
Bases:
ValueObject
,ValidationError
- 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
orInterface
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 queryurl (str) – The URL of the target endpoint
**kwargs –
auth
and/orclient
, passed tosnug.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
**kwargs –
auth
and/orclient
, passed tosnug.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 topartial(execute, **kwargs)
.- Parameters:
**kwargs –
url
,auth
, and/orclient
, passed toexecute()
- 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 topartial(execute_async, **kwargs)
.- Parameters:
**kwargs –
url
,auth
, and/orclient
, passed toexecute_async()
- Returns:
A callable to asynchronously execute GraphQL executables
- Return type:
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
- 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
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()
, orfrom_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. notNone
)- 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 asGenericScalar
subclasses.
- Returns:
The generated schema
- Return type:
- Raises:
IOError – If the file at given path cannot be read
- classmethod from_raw(raw_schema, module=None, scalars=())[source]#
Create a
Schema
from a raw JSON schema- Parameters:
raw_schema (List[Dict[str, JSON]]) – The raw GraphQL schema. I.e. the result of the
INTROSPECTION_QUERY
module (Optional[str], optional) – The name of the module to use when creating classes
scalars (Iterable[Type[Scalar]]) –
Scalar
classes to use in the schema. Scalars in the schema, but not in this sequence, will be defined asGenericScalar
subclasses.
- Returns:
The schema constructed from raw data
- Return type:
- 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 asGenericScalar
subclasses.module (Optional[str], optional) – The module name to set on the generated classes
**kwargs –
auth
orclient
, passed toexecute()
.
- Returns:
The generated schema
- Return type:
- 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