CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-graphql-core

GraphQL-core is a Python port of GraphQL.js, the JavaScript reference implementation for GraphQL.

Pending
Overview
Eval results
Files

execution.mddocs/

Primary Execution Functions

High-level functions that provide the complete GraphQL execution pipeline including parsing, validation, and execution in a single call. These are the primary entry points for executing GraphQL operations.

Capabilities

Asynchronous Execution

Execute GraphQL operations asynchronously, supporting async resolvers and middleware with complete error handling and context management.

async def graphql(
    schema: GraphQLSchema,
    source: Union[str, Source],
    root_value: Any = None,
    context_value: Any = None,
    variable_values: Optional[Dict[str, Any]] = None,
    operation_name: Optional[str] = None,
    field_resolver: Optional[GraphQLFieldResolver] = None,
    type_resolver: Optional[GraphQLTypeResolver] = None,
    middleware: Optional[Middleware] = None,
    execution_context_class: Optional[Type[ExecutionContext]] = None,
    is_awaitable: Optional[Callable[[Any], bool]] = None,
) -> ExecutionResult

Parameters:

  • schema: The GraphQL schema to use for validation and execution
  • source: GraphQL query string or Source object
  • root_value: Initial value passed to root-level resolvers
  • context_value: Context object available to all resolvers via resolve_info.context
  • variable_values: Variable values for parameterized queries
  • operation_name: Operation name when document contains multiple operations
  • field_resolver: Default field resolver function
  • type_resolver: Default type resolver for abstract types
  • middleware: Middleware to wrap resolver execution
  • execution_context_class: Custom execution context class
  • is_awaitable: Function to determine if values are awaitable

Returns: ExecutionResult with data, errors, and extensions

Usage Example

import asyncio
from graphql import GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLString, graphql

schema = GraphQLSchema(
    query=GraphQLObjectType(
        name='Query',
        fields={
            'hello': GraphQLField(
                GraphQLString,
                resolve=lambda obj, info: 'Hello World!'
            )
        }
    )
)

async def main():
    result = await graphql(schema, '{ hello }')
    print(result.data)  # {'hello': 'Hello World!'}

asyncio.run(main())

Synchronous Execution

Execute GraphQL operations synchronously, ensuring all resolvers complete without async behavior for simpler integration patterns.

def graphql_sync(
    schema: GraphQLSchema,
    source: Union[str, Source],
    root_value: Any = None,
    context_value: Any = None,
    variable_values: Optional[Dict[str, Any]] = None,
    operation_name: Optional[str] = None,
    field_resolver: Optional[GraphQLFieldResolver] = None,
    type_resolver: Optional[GraphQLTypeResolver] = None,
    middleware: Optional[Middleware] = None,
    execution_context_class: Optional[Type[ExecutionContext]] = None,
    check_sync: bool = False,
) -> ExecutionResult

Parameters: Same as graphql() except:

  • check_sync: If True, validates that no awaitable values are returned from resolvers

Returns: ExecutionResult with data, errors, and extensions

Usage Example

from graphql import GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLString, graphql_sync

schema = GraphQLSchema(
    query=GraphQLObjectType(
        name='Query',
        fields={
            'greeting': GraphQLField(
                GraphQLString,
                resolve=lambda obj, info, name='World': f'Hello {name}!'
            )
        }
    )
)

# Simple query
result = graphql_sync(schema, '{ greeting }')
print(result.data)  # {'greeting': 'Hello World!'}

# Query with variables
result = graphql_sync(
    schema, 
    'query($name: String) { greeting(name: $name) }',
    variable_values={'name': 'GraphQL'}
)
print(result.data)  # {'greeting': 'Hello GraphQL!'}

Execution Results

All execution functions return ExecutionResult objects containing the query results and any errors encountered.

class ExecutionResult:
    data: Optional[Dict[str, Any]]
    errors: Optional[List[GraphQLError]]
    extensions: Optional[Dict[str, Any]]
    
    def __init__(
        self,
        data: Optional[Dict[str, Any]] = None,
        errors: Optional[List[GraphQLError]] = None,
        extensions: Optional[Dict[str, Any]] = None,
    )

class FormattedExecutionResult(TypedDict):
    data: Optional[Dict[str, Any]]
    errors: Optional[List[GraphQLFormattedError]]
    extensions: Optional[Dict[str, Any]]

Properties:

  • data: Query result data as nested dictionaries, None if execution failed
  • errors: List of GraphQL errors encountered during execution
  • extensions: Additional metadata or debugging information

Error Handling Example

from graphql import graphql_sync, GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLString

def error_resolver(obj, info):
    raise Exception("Something went wrong!")

schema = GraphQLSchema(
    query=GraphQLObjectType(
        name='Query',
        fields={
            'error': GraphQLField(GraphQLString, resolve=error_resolver),
            'success': GraphQLField(GraphQLString, resolve=lambda obj, info: 'OK')
        }
    )
)

result = graphql_sync(schema, '{ error success }')
print(result.data)     # {'error': None, 'success': 'OK'}
print(len(result.errors))  # 1
print(result.errors[0].message)  # "Something went wrong!"

Types

# Import required types
from typing import Any, Dict, List, Optional, Union, Callable, Type
from graphql.type import GraphQLSchema, GraphQLFieldResolver, GraphQLTypeResolver
from graphql.execution import ExecutionContext, Middleware
from graphql.language import Source
from graphql.error import GraphQLError
from graphql.pyutils import AwaitableOrValue

# Core execution result type
ExecutionResult = class ExecutionResult:
    data: Optional[Dict[str, Any]]
    errors: Optional[List[GraphQLError]]
    extensions: Optional[Dict[str, Any]]

# Formatted result for serialization
FormattedExecutionResult = TypedDict('FormattedExecutionResult', {
    'data': Optional[Dict[str, Any]],
    'errors': Optional[List[GraphQLFormattedError]],
    'extensions': Optional[Dict[str, Any]]
})

# Union type for potentially awaitable values
AwaitableOrValue = Union[T, Awaitable[T]]

Install with Tessl CLI

npx tessl i tessl/pypi-graphql-core

docs

error-handling.md

execution-engine.md

execution.md

index.md

language.md

type-system.md

utilities.md

validation.md

tile.json