or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

error-handling.mdexecution-engine.mdexecution.mdindex.mdlanguage.mdtype-system.mdutilities.mdvalidation.md
tile.json

tessl/pypi-graphql-core

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

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/graphql-core@3.2.x

To install, run

npx @tessl/cli install tessl/pypi-graphql-core@3.2.0

index.mddocs/

GraphQL-Core

GraphQL-Core is a comprehensive Python port of GraphQL.js, providing the complete GraphQL specification implementation for Python. It enables developers to build and execute GraphQL schemas, handle queries, mutations, and subscriptions with full type safety and validation, supporting both synchronous and asynchronous execution.

Package Information

  • Package Name: graphql-core
  • Package Type: pypi
  • Language: Python
  • Installation: pip install graphql-core
  • Minimum Python Version: 3.6+

Core Imports

import graphql

Main functions:

from graphql import graphql, graphql_sync

Schema definition:

from graphql import (
    GraphQLSchema, 
    GraphQLObjectType, 
    GraphQLField, 
    GraphQLString,
    GraphQLInt,
    GraphQLFloat,
    GraphQLBoolean,
    GraphQLID
)

Basic Usage

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

# Define a simple schema
schema = GraphQLSchema(
    query=GraphQLObjectType(
        name='RootQueryType',
        fields={
            'hello': GraphQLField(
                GraphQLString,
                resolve=lambda obj, info: 'world'
            )
        }
    )
)

# Execute a query
query = '{ hello }'
result = graphql_sync(schema, query)
print(result.data)  # {'hello': 'world'}

Architecture

GraphQL-Core follows the GraphQL specification architecture with clear separation of concerns:

  • Language Module: Parsing GraphQL documents into Abstract Syntax Trees (AST), lexical analysis, and AST manipulation
  • Type System: Schema definition, built-in scalar types, custom types, directives, and type validation
  • Validation Module: Query validation against schema using specification-defined rules
  • Execution Module: Query execution engine with support for resolvers, middleware, and subscriptions
  • Utilities Module: Schema introspection, schema building from SDL, type comparisons, and development tools
  • Error Handling: Comprehensive error reporting with location information and extensible error formatting

Capabilities

Primary Execution Functions

High-level functions to execute GraphQL operations against a schema with complete parsing, validation, and execution pipeline.

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

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

Primary Execution

Language Processing and AST

Parse GraphQL documents, manipulate AST nodes, and work with GraphQL source code including lexical analysis, parsing, and AST visitor patterns.

def parse(source: Union[str, Source]) -> DocumentNode
def parse_value(source: Union[str, Source]) -> ValueNode
def parse_type(source: Union[str, Source]) -> TypeNode
def print_ast(ast: Node) -> str
def visit(root: Node, visitor: Visitor) -> Any

class Source:
    def __init__(self, body: str, name: str = "GraphQL request")

class Lexer:
    def __init__(self, source: Source)

Language Processing

Type System and Schema Definition

Build GraphQL schemas with types, fields, directives, and validation. Includes built-in scalar types and comprehensive type checking.

class GraphQLSchema:
    def __init__(
        self,
        query: Optional[GraphQLObjectType] = None,
        mutation: Optional[GraphQLObjectType] = None,
        subscription: Optional[GraphQLObjectType] = None,
        types: Optional[Sequence[GraphQLNamedType]] = None,
        directives: Optional[Sequence[GraphQLDirective]] = None,
        description: Optional[str] = None,
        extensions: Optional[Dict[str, Any]] = None,
    )

class GraphQLObjectType:
    def __init__(
        self,
        name: str,
        fields: Union[Thunk[GraphQLFieldMap], GraphQLFieldMap],
        interfaces: Optional[Thunk[Sequence[GraphQLInterfaceType]]] = None,
        is_type_of: Optional[GraphQLIsTypeOfFn] = None,
        description: Optional[str] = None,
        extensions: Optional[Dict[str, Any]] = None,
    )

class GraphQLField:
    def __init__(
        self,
        type_: GraphQLOutputType,
        args: Optional[GraphQLArgumentMap] = None,
        resolve: Optional[GraphQLFieldResolver] = None,
        subscribe: Optional[GraphQLFieldResolver] = None,
        description: Optional[str] = None,
        deprecation_reason: Optional[str] = None,
        extensions: Optional[Dict[str, Any]] = None,
    )

Type System

Query Validation

Validate GraphQL documents against schemas using specification-defined validation rules and custom validation logic.

def validate(schema: GraphQLSchema, document: DocumentNode, rules: Optional[Sequence[ValidationRule]] = None) -> List[GraphQLError]

class ValidationContext:
    def __init__(self, schema: GraphQLSchema, document: DocumentNode, type_info: TypeInfo, on_error: Callable[[GraphQLError], None])

specified_rules: List[ValidationRule]

Query Validation

Query Execution Engine

Execute validated GraphQL operations with resolver functions, middleware support, and subscription handling.

def execute(
    schema: GraphQLSchema,
    document: DocumentNode,
    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,
    subscribe_field_resolver: Optional[GraphQLFieldResolver] = None,
    middleware: Optional[Middleware] = None,
    execution_context_class: Optional[Type[ExecutionContext]] = None,
    is_awaitable: Optional[Callable[[Any], bool]] = None,
) -> AwaitableOrValue[ExecutionResult]

def execute_sync(
    schema: GraphQLSchema,
    document: DocumentNode,
    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

class ExecutionResult:
    data: Optional[Dict[str, Any]]
    errors: Optional[List[GraphQLError]]
    extensions: Optional[Dict[str, Any]]

Query Execution

Schema Utilities and Introspection

Build schemas from SDL, perform introspection, compare schemas, and manipulate GraphQL type information for tooling and development.

def build_schema(
    source: Union[str, Source],
    assume_valid: bool = False,
    assume_valid_sdl: bool = False,
    no_location: bool = False,
    allow_legacy_fragment_variables: bool = False,
) -> GraphQLSchema
def build_ast_schema(document_ast: DocumentNode) -> GraphQLSchema
def build_client_schema(introspection: Dict[str, Any]) -> GraphQLSchema
def extend_schema(schema: GraphQLSchema, document_ast: DocumentNode) -> GraphQLSchema
def print_schema(schema: GraphQLSchema) -> str
def get_introspection_query(description: bool = True) -> str
def introspection_from_schema(schema: GraphQLSchema) -> Dict[str, Any]
def find_breaking_changes(old_schema: GraphQLSchema, new_schema: GraphQLSchema) -> List[BreakingChange]
def find_dangerous_changes(old_schema: GraphQLSchema, new_schema: GraphQLSchema) -> List[DangerousChange]

class TypeInfo:
    def __init__(self, schema: GraphQLSchema, initial_type: Optional[GraphQLType] = None)

Schema Utilities

Error Handling and Debugging

Handle GraphQL errors with location information, formatted error responses, and extensible error reporting.

class GraphQLError(Exception):
    def __init__(
        self,
        message: str,
        nodes: Optional[Union[Node, Sequence[Node]]] = None,
        source: Optional[Source] = None,
        positions: Optional[Sequence[int]] = None,
        path: Optional[Sequence[Union[str, int]]] = None,
        original_error: Optional[Exception] = None,
        extensions: Optional[Dict[str, Any]] = None,
    )

class GraphQLSyntaxError(GraphQLError):
    pass

def located_error(original_error: Exception, nodes: Optional[Union[Node, Sequence[Node]]] = None, path: Optional[Sequence[Union[str, int]]] = None) -> GraphQLError

# Type definitions
GraphQLFormattedError = Dict[str, Any]
GraphQLErrorExtensions = Dict[str, Any]

Error Handling

Types

Core Types

# Built-in scalar types
GraphQLInt: GraphQLScalarType
GraphQLFloat: GraphQLScalarType
GraphQLString: GraphQLScalarType
GraphQLBoolean: GraphQLScalarType
GraphQLID: GraphQLScalarType

# Type system types
GraphQLType = Union[GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull]
GraphQLInputType = Union[GraphQLScalarType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull]
GraphQLOutputType = Union[GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLList, GraphQLNonNull]

# Schema types
from typing import Any, Dict, List, Optional, Union, Sequence, Callable, Type
from graphql.pyutils import Undefined, UndefinedType

# Resolver function types
GraphQLFieldResolver = Callable[..., Any]
GraphQLTypeResolver = Callable[..., Any]
GraphQLIsTypeOfFn = Callable[..., bool]

# Execution types
class ExecutionResult:
    data: Optional[Dict[str, Any]]
    errors: Optional[List[GraphQLError]]
    extensions: Optional[Dict[str, Any]]

# AST node types
class DocumentNode:
    kind: str
    definitions: List[DefinitionNode]

class OperationDefinitionNode:
    kind: str
    operation: OperationType
    name: Optional[NameNode]
    variable_definitions: Optional[List[VariableDefinitionNode]]
    directives: Optional[List[DirectiveNode]]
    selection_set: SelectionSetNode

# Version information
version: str
version_info: VersionInfo
version_js: str
version_info_js: VersionInfo

class VersionInfo:
    major: int
    minor: int
    micro: int
    releaselevel: str
    serial: int