API reference
Following items are importable directly from ariadne
package:
EnumType
EnumType(name, values)
Bindable used for mapping python values to enumeration members defined in GraphQL schema.
Required arguments
name
str
with name of enumeration type defined in schema.
values
dict
, enum.Enum
or enum.IntEnum
instance that defines mappings between Enum members and values
Example
Enum defined in schema:
enum ErrorType {
NOT_FOUND
PERMISSION_DENIED
VALIDATION_ERROR
}
Python mapping using dict
:
from ariadne import EnumType
error_type_enum = EnumType(
"ErrorType",
{
"NOT_FOUND": "NotFound",
"PERMISSION_DENIED": "PermissionDenied",
"VALIDATION_ERROR": "ValidationError",
}
)
Python mapping using enum.Enum
:
from enum import Enum
from ariadne import EnumType
class ErrorType(Enum):
NOT_FOUND = "NotFound"
PERMISSION_DENIED = "PermissionDenied"
VALIDATION_ERROR = "ValidationError"
error_type_enum = EnumType("ErrorType", ErrorType)
FallbackResolversSetter
FallbackResolversSetter()
Bindable used for setting default resolvers on schema object types.
Use
fallback_resolvers
instead of instantiatingFallbackResolversSetter
.
Custom default resolver example
You can create custom class extending FallbackResolversSetter
to set custom default resolver on your GraphQL object types:
from ariadne import FallbackResolversSetter
def custom_resolver(obj, info, **kwargs) -> Any:
try:
return obj.get(info.field_name)
except AttributeError:
return getattr(obj, info.field_name, None)
class CustomFallbackResolversSetter(FallbackResolversSetter):
def add_resolver_to_field(self, field_name, field_object):
if field_object.resolve is None:
field_object.resolve = custom_resolver
InterfaceType
InterfaceType(name, type_resolver=None)
Bindable used for setting Python logic for GraphQL interfaces. Extends ObjectType
.
Because
InterfaceType
extendsObjectType
, it can also be used to set field resolvers.InterfaceType will set its resolvers on fields of GraphQL types implementing the interface, but only if there is no resolver already set on the field.
Required arguments
name
str
with name of interface type defined in schema.
Optional arguments
type_resolver
Valid resolver that is used to resolve the str
with name of GraphQL type to which obj
(passed as first argument) belongs to. Receives GraphQLResolveInfo
instance as second argument.
Methods
set_type_resolver
InterfaceType.set_type_resolver(type_resolver)
Sets type_resolver
as type resolver used to resolve the str
with name of GraphQL type to which obj
(passed as first argument) belongs to. Receives GraphQLResolveInfo
instance as second argument.
Returns value passed to type_resolver
argument.
type_resolver
Decorator counterpart of set_type_resolver
:
search_result = InterfaceType("SearchResult")
@search_result.type_resolver
def resolve_search_result_type(obj, info):
...
Decorator doesn't change or wrap the decorated function into any additional logic.
Example
Interface type for search result that can be User
or Thread
, that defines the url field and sets default resolver for it:
interface SearchResult {
url: String!
}
search_result = InterfaceType("SearchResult")
@search_result.type_resolver
def resolve_search_result_type(obj, info):
if isinstance(obj, User):
return "User"
if isinstance(obj, Thread):
return "Thread"
@search_result.field("url")
def resolve_search_result_url(obj, info):
return obj.get_absolute_url()
MutationType
MutationType()
Bindable used for setting Python logic for GraphQL mutation type. Has the same API as ObjectType
, but has GraphQL type name hardcoded to Mutation
.
This is an convenience utility that can be used in place of of
ObjectType("Mutation")
.
ObjectType
ObjectType(name)
Bindable used for setting Python logic for GraphQL object types.
Required arguments
name
str
with name of an object type defined in schema.
Methods
field
Decorator that takes single parameter, name
of GraphQL field, and sets decorated callable as resolver for it:
user = ObjectType("User")
@user.field("posts")
def resolve_posts(obj, info):
...
Decorator doesn't change or wrap the decorated function into any additional logic.
set_alias
ObjectType.set_alias(name, to)
Makes a field name
defined in the schema resolve to property to
of an object.
For example, if you want field username
from schema resolve to attribute user_name
of Python object, you can set an alias:
user = ObjectType("User")
user.set_alias("username", "user_name")
set_field
ObjectType.set_field(name, resolver)
Sets resolver
callable as resolver that will be used to resolve the GraphQL field named name
.
Returns value passed to resolver
argument.
QueryType
QueryType()
Bindable used for setting Python logic for GraphQL mutation type. Has the same API as ObjectType
, but has GraphQL type name hardcoded to Query
.
This is an convenience utility that can be used in place of of
ObjectType("Query")
.
ScalarType
ScalarType(name, *, serializer=None, value_parser=None, literal_parser=None)
Bindable used for setting Python logic for GraphQL scalar type.
Required arguments
name
str
with name of scalar type defined in schema.
serializer
Callable that is called to convert scalar value into JSON-serializable form.
value_parser
Callable that is called to convert JSON-serialized value back into Python form.
literal_parser
Callable that is called to convert AST ValueNode
value into Python form.
Methods
literal_parser
Decorator that sets decorated callable as literal parser for the scalar:
datetime = ScalarType("DateTime")
@datetime.literal_parser
def parse_datetime_literal(ast):
...
Decorator doesn't change or wrap the decorated function into any additional logic.
serializer
Decorator that sets decorated callable as serializer for the scalar:
datetime = ScalarType("DateTime")
@datetime.serializer
def serialize_datetime(value):
...
Decorator doesn't change or wrap the decorated function into any additional logic.
set_serializer
ScalarType.set_serializer(serializer)
Sets serializer
callable as serializer for the scalar.
set_literal_parser
ScalarType.set_value_parser(literal_parser)
Sets literal_parser
callable as literal parser for the scalar.
set_value_parser
ScalarType.set_value_parser(value_parser)
Sets value_parser
callable as value parser for the scalar.
As convenience, this function will also set literal parser, if none was set already.
value_parser
Decorator that sets decorated callable as value parser for the scalar:
datetime = ScalarType("DateTime")
@datetime.value_parser
def parse_datetime_value(value):
...
Decorator doesn't change or wrap the decorated function into any additional logic.
As convenience, this decorator will also set literal parser, if none was set already.
Example
Read-only scalar that converts datetime
object to string containing ISO8601 formatted date:
datetime = ScalarType("DateTime")
@datetime.serializer
def serialize_datetime(value):
return value.isoformat()
Bidirectional scalar that converts date
object to ISO8601 formatted date and reverses it back:
from datetime import date
date_scalar = ScalarType("Date")
@date.serializer
def serialize_datetime(value):
return value.isoformat()
@date.value_parser
def serialize_datetime(value):
return date.strptime(value, "%Y-%m-%d")
SchemaBindable
class SchemaBindable()
Base class for bindables.
Methods
bind_to_schema
SchemaBindable.bind_to_schema(schema)
Method called by make_executable_schema
with single argument being instance of GraphQL schema. Extending classes should override this method with custom logic that binds business mechanic to schema.
SnakeCaseFallbackResolversSetter
SnakeCaseFallbackResolversSetter()
Bindable used for setting default resolvers on schema object types. Subclasses FallbackResolversSetter
and sets default resolver that performs case conversion between GraphQL's camelCase
and Python's snake_case
:
type User {
"Default resolver for this field will read value from contact_address"
contactAddress: String
}
Use
fallback_resolvers
instead of instantiatingSnakeCaseFallbackResolversSetter
.
SubscriptionType
SubscriptionType()
Bindable used for setting Python logic for GraphQL subscription type.
Like
QueryType
andMutationType
this type is hardcoded to bind only toSubscription
type in schema.
Methods
field
Decorator that takes single parameter, name
of GraphQL field, and sets decorated callable as resolver for it.
subscription = SubscriptionType()
@subscription.field("alerts")
def resolve_alerts(obj, info):
...
Decorator doesn't change or wrap the decorated function into any additional logic.
Root resolvers set on subscription type are called with value returned by field's
source
resolver as first argument.
set_field
SubscriptionType.set_field(name, resolver)
Sets resolver
callable as resolver that will be used to resolve the GraphQL field named name
.
Returns value passed to resolver
argument.
Root resolvers set on subscription type are called with value returned by field's
source
resolver as first argument.
set_source
SubscriptionType.set_source(name, generator)
Sets generator
generator as source that will be used to resolve the GraphQL field named name
.
Returns value passed to generator
argument.
source
Decorator that takes single parameter, name
of GraphQL field, and sets decorated generator as source for it.
subscription = SubscriptionType()
@subscription.source("alerts")
async def alerts_generator(obj, info):
...
Decorator doesn't change or wrap the decorated function into any additional logic.
Example
Simple counter API that counts to 5 and ends subscription:
type Subscription {
counter: Int
}
import asyncio
subscription = SubscriptionType()
@subscription.source("counter")
async def counter_generator(obj, info):
for i in range(5):
await asyncio.sleep(1)
yield i
@subscription.field("counter")
def counter_resolver(count, info):
return count
UnionType
UnionType(name, type_resolver=None)
Bindable used for setting Python logic for GraphQL union type.
Methods
set_type_resolver
UnionType.set_type_resolver(type_resolver)
Sets type_resolver
as type resolver used to resolve the str
with name of GraphQL type to which obj
(passed as first argument) belongs to. Receives GraphQLResolveInfo
instance as second argument.
Returns value passed to type_resolver
argument.
type_resolver
Decorator counterpart of set_type_resolver
:
search_result = UnionType("SearchResult")
@search_result.type_resolver
def resolve_search_result_type(obj, info):
...
Decorator doesn't change or wrap the decorated function into any additional logic.
Example
Union type for search result that can be User
or Thread
:
union SearchResult = User | Thread
search_result = UnionType("SearchResult")
@search_result.type_resolver
def resolve_search_result_type(obj, info):
if isinstance(obj, User):
return "User"
if isinstance(obj, Thread):
return "Thread"
convert_camel_case_to_snake
convert_camel_case_to_snake(graphql_name)
Utility function that converts GraphQL name written in camelCase
to its Python snake_case
counterpart.
default_resolver
def default_resolver(parent, info)
Default resolver used by Ariadne. If parent
is dict
, will use dict.get(info.field_name)
to resolve the value. Uses getattr(parent, info.field_name, None)
otherwise.
fallback_resolvers
fallback_resolvers
Bindable instance of FallbackResolversSetter
.
format_error
def format_error(error, debug=False)
Default error formatter used by Ariadne. Takes instance of GraphQLError
as first argument and debug flag as second.
Returns dict
containing formatted error data ready for returning to API client.
If debug
is True
, updates returned data extensions
key with exception
dict
that contains traceback to original Python exception and its context variables.
get_error_extension
def get_error_extension(error)
Takes GraphQLError
instance as only argument and returns dict
with traceback and context of original Python exception. If error was not caused by exception in resolver, returns None
instead.
gql
def gql(value)
Utility function that takes GraphQL string as only argument, validates it and returns same string unchanged or raises GraphQLError
if string was invalid.
Wrapping GraphQL strings declarations with this utility will make errors easier to track down and debug, as their traceback will point to place of declaration instead of Ariadne internals:
type_defs = gql("""
type Query {
username: String!
}
""")
graphql
async def graphql(schema, data, *, root_value=None, context_value=None, logger=None, debug=False, validation_rules, error_formatter, middleware, **kwargs)
Asynchronously executes query against schema.
Returns a tuple of two values:
success
-True
ifdata
was correct andFalse
if not. Depending on this value GraphQL server should return status code200
or400
.response
- response data that should be JSON-encoded and sent to client.
This function is an asynchronous coroutine so you will need to
await
on the returned value.
Coroutines will not work under WSGI. If your server uses WSGI (Django and Flask do), use
graphql_sync
instead.
Required arguments
schema
An executable schema created using make_executable_schema
.
data
Decoded input data sent by the client (eg. for POST requests in JSON format, pass in the structure decoded from JSON). Exact shape of data
depends on the query type and protocol.
Configuration options
context_value
The context value passed to all resolvers (it's common for your context to include the request object specific to your web framework). It can be of any type and is available as the context
attribute of GraphQLResolveInfo
instance passed as second argument to all resolvers.
root_value
The value passed to the root-level resolvers. Can be of any type.
If type is callable
it will be called with two arguments:
context
- containing currentcontext_value
.document
-DocumentNode
that was result of parsing current GraphQL query
Callable return value will then be used as final root_value
passed to resolvers.
logger
String with the name of logger that should be used to log GraphQL errors. Defaults to ariadne
.
debug
If True
will cause the server to include debug information in error responses.
validation_rules
optional additional validators (as defined by graphql.validation.rules
) to run before attempting to execute the query (the standard validators defined by the GraphQL specification are always used and There's no need to provide them here).
error_formatter
An optional custom function to use for formatting errors, the function will be passed two parameters: a GraphQLError
exception instance, and the value of the debug
switch.
Defaults to format_error
.
middleware
Optional middleware to wrap the resolvers with.
graphql_sync
def graphql(schema, data, *, root_value=None, context_value=None, debug=False, validation_rules, error_formatter, middleware, **kwargs)
Synchronously executes query against schema. Configuration options are exactly the same as in graphql
.
Use this function instead of
graphql
to run queries in synchronous servers (WSGI, Django, Flask).
load_schema_from_path
def load_schema_from_path(path)
Loads GraphQL schema from path
using different strategy depending on path
's type:
- If
path
is single file, reads it. - If
path
is directory, walks it recursively loading all.graphql
files within it.
Files are validated using the same logic that gql
uses, concatenated into single string and returned.
make_executable_schema
def make_executable_schema(type_defs, bindables=None)
Takes two arguments:
type_defs
- string or list of strings with valid GraphQL types definitions.bindables
- bindable or list of bindables with Python logic to add to schema. Optional.
Returns GraphQLSchema
instance that can be used to run queries on.
resolve_to
def resolve_to(name)
Returns default_resolver
that always resolves to named attribute. Used to create aliases by ObjectType.set_alias
.
snake_case_fallback_resolvers
snake_case_fallback_resolvers
Bindable instance of SnakeCaseFallbackResolversSetter
.
subscribe
async def subscribe(schema, data, *, root_value=None, context_value=None, debug=False, validation_rules, error_formatter, **kwargs)
Asynchronously executes subscription query against schema, usually made over the websocket. Takes same arguments and options as graphql
except middleware
.
This function is an asynchronous coroutine so you will need to
await
on the returned value.
Coroutines will not work under WSGI. If your server uses WSGI (Django and Flask do), use
graphql_sync
instead.