0
# Graphene
1
2
Graphene is a Python library for building GraphQL schemas and APIs quickly and easily. It provides a complete API for creating GraphQL servers with support for various data sources, built-in Relay support for pagination and mutations, and seamless integration with GraphQL clients. The library offers a declarative approach to defining GraphQL schemas using Python classes, automatic query resolution, field-level permissions and validation, and extensive customization options for complex GraphQL operations.
3
4
## Package Information
5
6
- **Package Name**: graphene
7
- **Language**: Python
8
- **Installation**: `pip install graphene`
9
10
## Core Imports
11
12
```python
13
import graphene
14
```
15
16
Common imports for building schemas:
17
18
```python
19
from graphene import (
20
ObjectType, String, Int, Field, Schema,
21
Mutation, List, NonNull, Argument
22
)
23
```
24
25
For Relay support:
26
27
```python
28
from graphene import (
29
Node, Connection, ConnectionField,
30
ClientIDMutation, GlobalID
31
)
32
```
33
34
## Basic Usage
35
36
```python
37
import graphene
38
39
# Define a basic ObjectType
40
class Person(graphene.ObjectType):
41
name = graphene.String(required=True)
42
age = graphene.Int()
43
email = graphene.String()
44
45
# Define a Query
46
class Query(graphene.ObjectType):
47
person = graphene.Field(Person)
48
people = graphene.List(Person)
49
50
def resolve_person(self, info):
51
return Person(name="Alice", age=30, email="alice@example.com")
52
53
def resolve_people(self, info):
54
return [
55
Person(name="Alice", age=30, email="alice@example.com"),
56
Person(name="Bob", age=25, email="bob@example.com")
57
]
58
59
# Define a Mutation
60
class CreatePerson(graphene.Mutation):
61
class Arguments:
62
name = graphene.String(required=True)
63
age = graphene.Int()
64
email = graphene.String()
65
66
person = graphene.Field(Person)
67
68
def mutate(self, info, name, age=None, email=None):
69
person = Person(name=name, age=age, email=email)
70
return CreatePerson(person=person)
71
72
class Mutation(graphene.ObjectType):
73
create_person = CreatePerson.Field()
74
75
# Create the schema
76
schema = graphene.Schema(query=Query, mutation=Mutation)
77
78
# Execute a query
79
result = schema.execute('''
80
query {
81
person {
82
name
83
age
84
85
}
86
people {
87
name
88
age
89
}
90
}
91
''')
92
93
print(result.data)
94
```
95
96
## Architecture
97
98
Graphene follows the GraphQL specification and provides a declarative Python API built on these key concepts:
99
100
- **Type System**: Comprehensive GraphQL type system with Python classes for ObjectType, Interface, Union, Enum, and Scalar types
101
- **Schema Definition**: Central Schema class that combines query, mutation, and subscription operations with type definitions
102
- **Field Resolution**: Automatic resolver discovery and custom resolver support for connecting GraphQL fields to data sources
103
- **Relay Integration**: Full Relay specification compliance including Node interface, connections for pagination, and mutations with client IDs
104
- **Metaclass System**: Extensive use of metaclasses for declarative API definition and automatic field collection from Python class definitions
105
106
This architecture enables high reusability across web APIs, microservices, and any application requiring a GraphQL interface.
107
108
## Capabilities
109
110
### Type System
111
112
Core GraphQL type system including object types, scalar types, interfaces, unions, enums, input types, and field definitions. Provides the foundation for building GraphQL schemas with full type safety and validation.
113
114
```python { .api }
115
class ObjectType(BaseType): ...
116
class Interface(BaseType): ...
117
class Union(UnmountedType, BaseType): ...
118
class Enum(EnumMeta): ...
119
class InputObjectType(UnmountedType, BaseType): ...
120
121
class Field(MountedType): ...
122
class InputField(MountedType): ...
123
class Argument(MountedType): ...
124
125
# Scalar types
126
class String(Scalar): ...
127
class Int(Scalar): ...
128
class Float(Scalar): ...
129
class Boolean(Scalar): ...
130
class ID(Scalar): ...
131
class UUID(Scalar): ...
132
class DateTime(Scalar): ...
133
class Date(Scalar): ...
134
class Time(Scalar): ...
135
class Decimal(Scalar): ...
136
class JSONString(Scalar): ...
137
class Base64(Scalar): ...
138
class BigInt(Scalar): ...
139
140
# Structure modifiers
141
class List(Structure): ...
142
class NonNull(Structure): ...
143
```
144
145
[Type System](./type-system.md)
146
147
### Schema and Execution
148
149
Schema definition, query execution, and resolver management. Handles the creation of GraphQL schemas and provides synchronous and asynchronous execution capabilities with comprehensive resolver support.
150
151
```python { .api }
152
class Schema:
153
def __init__(self, query=None, mutation=None, subscription=None, types=None, directives=None, auto_camelcase=True): ...
154
def execute(self, query, *args, **kwargs): ...
155
def execute_async(self, query, *args, **kwargs): ...
156
def subscribe(self, query, *args, **kwargs): ...
157
def introspect(self): ...
158
def lazy(self, type): ...
159
160
class Mutation(ObjectType): ...
161
class Dynamic(MountedType): ...
162
class Context: ...
163
```
164
165
[Schema and Execution](./schema-execution.md)
166
167
### Relay Integration
168
169
Complete GraphQL Relay specification support including Node interface for global object identification, connection-based pagination, client ID mutations, and flexible global ID type systems.
170
171
```python { .api }
172
class Node(Interface): ...
173
def is_node(objecttype): ...
174
175
class GlobalID(Field): ...
176
class BaseGlobalIDType: ...
177
class DefaultGlobalIDType(BaseGlobalIDType): ...
178
class SimpleGlobalIDType(BaseGlobalIDType): ...
179
class UUIDGlobalIDType(BaseGlobalIDType): ...
180
181
class Connection(ObjectType): ...
182
class ConnectionField(Field): ...
183
class PageInfo(ObjectType): ...
184
185
class ClientIDMutation(Mutation): ...
186
```
187
188
[Relay Integration](./relay.md)
189
190
## Utility Functions
191
192
```python { .api }
193
# Version information
194
VERSION = (3, 4, 3, "final", 0)
195
__version__ = "3.4.3"
196
197
def lazy_import(dotted_path, dotted_attributes=None):
198
"""
199
Creates lazy import callables to avoid circular imports.
200
201
Args:
202
dotted_path (str): The module path to import from
203
dotted_attributes (str, optional): The attributes to import
204
205
Returns:
206
Partial function for delayed import
207
"""
208
209
def resolve_only_args(func):
210
"""
211
Decorator that strips 'info' parameter from resolver signatures.
212
213
Status: Deprecated - not recommended for new code
214
"""
215
```
216
217
## Types
218
219
```python { .api }
220
# From graphql-core
221
class ResolveInfo:
222
"""
223
GraphQL execution info object containing execution context.
224
225
Attributes:
226
field_name: Current field name
227
return_type: Expected return type
228
parent_type: Parent GraphQL type
229
schema: GraphQL schema
230
fragments: Query fragments
231
operation: GraphQL operation
232
variable_values: Query variables
233
context: Execution context object
234
"""
235
```