A library for creating GraphQL APIs using dataclasses and type annotations with extensive framework integration support.
npx @tessl/cli install tessl/pypi-strawberry-graphql@0.281.00
# Strawberry GraphQL
1
2
Strawberry GraphQL is a modern Python library for building GraphQL APIs using dataclasses and type annotations. It provides a decorator-based approach that allows developers to define GraphQL schemas using Python types, making GraphQL API development more Pythonic and intuitive. The library supports multiple web frameworks including FastAPI, Django, Flask, Starlette, and others through dedicated integrations, enabling seamless integration into existing Python web applications.
3
4
## Package Information
5
6
- **Package Name**: strawberry-graphql
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install strawberry-graphql`
10
11
## Core Imports
12
13
```python
14
import strawberry
15
```
16
17
For specific components:
18
19
```python
20
from strawberry import (
21
type, input, interface, enum, scalar, union,
22
field, mutation, subscription, argument,
23
Schema, Info, BasePermission, ID
24
)
25
```
26
27
## Basic Usage
28
29
```python
30
import strawberry
31
from typing import List
32
33
@strawberry.type
34
class User:
35
id: strawberry.ID
36
name: str
37
email: str
38
age: int = strawberry.field(description="User's age in years")
39
40
@strawberry.field
41
def display_name(self) -> str:
42
return f"{self.name} ({self.email})"
43
44
@strawberry.type
45
class Query:
46
@strawberry.field
47
def users(self) -> List[User]:
48
return [
49
User(id="1", name="Alice", email="alice@example.com", age=30),
50
User(id="2", name="Bob", email="bob@example.com", age=25)
51
]
52
53
@strawberry.field
54
def user(self, id: strawberry.ID) -> User:
55
# Fetch user by ID logic here
56
return User(id=id, name="Alice", email="alice@example.com", age=30)
57
58
@strawberry.type
59
class Mutation:
60
@strawberry.mutation
61
def create_user(self, name: str, email: str, age: int) -> User:
62
# Create user logic here
63
return User(id="new", name=name, email=email, age=age)
64
65
schema = strawberry.Schema(query=Query, mutation=Mutation)
66
67
# Execute a query
68
result = schema.execute_sync('''
69
query {
70
users {
71
id
72
name
73
displayName
74
}
75
}
76
''')
77
```
78
79
## Architecture
80
81
Strawberry GraphQL is built around several key architectural components:
82
83
- **Decorator-Based Type System**: Uses Python decorators (`@strawberry.type`, `@strawberry.field`) to define GraphQL schemas directly from Python classes and functions
84
- **Type Safety**: Leverages Python type hints and dataclasses for automatic GraphQL type generation and runtime validation
85
- **Schema Generation**: Automatically generates GraphQL schemas from decorated Python classes, reducing boilerplate code
86
- **Framework Integrations**: Provides dedicated integrations for popular web frameworks (FastAPI, Django, Flask, etc.) with framework-specific views and middleware
87
- **Extension System**: Modular extension system for adding custom functionality like validation, caching, authentication, and monitoring
88
- **Federation Support**: Built-in Apollo Federation support for microservices architectures
89
- **Relay Compatibility**: Full Relay specification implementation for React applications
90
91
## Capabilities
92
93
### Core Type System
94
95
Essential decorators and types for defining GraphQL schemas using Python dataclasses and type annotations. These form the foundation of any Strawberry GraphQL application.
96
97
```python { .api }
98
def type(cls=None, *, name: str = None, description: str = None) -> Any: ...
99
def input(cls=None, *, name: str = None, description: str = None) -> Any: ...
100
def interface(cls=None, *, name: str = None, description: str = None) -> Any: ...
101
def enum(cls=None, *, name: str = None, description: str = None) -> Any: ...
102
def scalar(cls=None, *, serialize: Callable = None, parse_value: Callable = None) -> Any: ...
103
def union(name: str, types: Tuple[Type, ...]) -> Any: ...
104
```
105
106
[Core Type System](./core-types.md)
107
108
### Field Definitions and Resolvers
109
110
Field definition system with custom resolvers, descriptions, permissions, and advanced configuration options for GraphQL fields.
111
112
```python { .api }
113
def field(
114
resolver: Callable = None,
115
*,
116
name: str = None,
117
description: str = None,
118
deprecation_reason: str = None,
119
permission_classes: List[Type[BasePermission]] = None
120
) -> Any: ...
121
122
def mutation(
123
resolver: Callable = None,
124
*,
125
name: str = None,
126
description: str = None,
127
permission_classes: List[Type[BasePermission]] = None
128
) -> Any: ...
129
130
def subscription(
131
resolver: Callable = None,
132
*,
133
name: str = None,
134
description: str = None,
135
permission_classes: List[Type[BasePermission]] = None
136
) -> Any: ...
137
138
def argument(
139
name: str = None,
140
description: str = None,
141
default: Any = None
142
) -> Any: ...
143
```
144
145
[Field Definitions](./fields-resolvers.md)
146
147
### Schema and Execution
148
149
Schema creation and query execution system with support for queries, mutations, subscriptions, and context management.
150
151
```python { .api }
152
class Schema:
153
def __init__(
154
self,
155
query: Type = None,
156
mutation: Type = None,
157
subscription: Type = None,
158
extensions: List[SchemaExtension] = None
159
): ...
160
161
def execute_sync(self, query: str, variable_values: Dict = None, context_value: Any = None) -> ExecutionResult: ...
162
async def execute(self, query: str, variable_values: Dict = None, context_value: Any = None) -> ExecutionResult: ...
163
async def subscribe(self, query: str, variable_values: Dict = None, context_value: Any = None) -> AsyncIterator: ...
164
165
class Info:
166
context: Any
167
field_name: str
168
operation_name: str
169
path: List[str]
170
return_type: Type
171
schema: Schema
172
variable_values: Dict[str, Any]
173
```
174
175
[Schema and Execution](./schema-execution.md)
176
177
### Framework Integrations
178
179
Web framework integrations providing GraphQL endpoints for popular Python web frameworks with framework-specific features and middleware.
180
181
```python { .api }
182
# FastAPI
183
class GraphQLRouter:
184
def __init__(self, schema: Schema, path: str = "/graphql"): ...
185
186
# ASGI
187
class GraphQL:
188
def __init__(
189
self,
190
schema: Schema,
191
graphql_ide: str = "graphiql",
192
allow_queries_via_get: bool = False
193
): ...
194
195
# Django, Flask, Sanic, etc.
196
class GraphQLView:
197
def __init__(self, schema: Schema): ...
198
```
199
200
[Framework Integrations](./framework-integrations.md)
201
202
### Extensions System
203
204
Schema and field-level extensions for adding custom functionality like validation, caching, security, and monitoring to GraphQL operations.
205
206
```python { .api }
207
class SchemaExtension:
208
def on_request_start(self): ...
209
def on_request_end(self): ...
210
def on_validation_start(self): ...
211
def on_validation_end(self): ...
212
def on_parsing_start(self): ...
213
def on_parsing_end(self): ...
214
215
class FieldExtension:
216
def apply(self, field: StrawberryField) -> StrawberryField: ...
217
218
# Built-in extensions
219
class QueryDepthLimiter(SchemaExtension): ...
220
class ValidationCache(SchemaExtension): ...
221
class ParserCache(SchemaExtension): ...
222
class DisableIntrospection(SchemaExtension): ...
223
```
224
225
[Extensions System](./extensions.md)
226
227
### Apollo Federation
228
229
Apollo Federation support for building distributed GraphQL architectures with multiple services and schema composition.
230
231
```python { .api }
232
# Federation schema
233
class Schema:
234
def __init__(
235
self,
236
query: Type = None,
237
mutation: Type = None,
238
enable_federation_2: bool = False
239
): ...
240
241
# Federation decorators
242
def type(cls=None, *, keys: List[str] = None, extend: bool = False): ...
243
def field(resolver=None, *, external: bool = False, requires: str = None, provides: str = None): ...
244
```
245
246
[Apollo Federation](./federation.md)
247
248
### Relay Specification
249
250
Complete Relay specification implementation with Node interface, connections, pagination, and global object identification.
251
252
```python { .api }
253
class Node:
254
id: NodeID
255
256
class Connection:
257
edges: List[Edge]
258
page_info: PageInfo
259
260
class Edge:
261
node: Node
262
cursor: str
263
264
class PageInfo:
265
has_next_page: bool
266
has_previous_page: bool
267
start_cursor: str
268
end_cursor: str
269
270
def connection(resolver: Callable) -> Any: ...
271
```
272
273
[Relay Specification](./relay.md)
274
275
### Data Loading and Utilities
276
277
Utilities for efficient data loading, file uploads, type conversions, and common GraphQL patterns.
278
279
```python { .api }
280
class DataLoader:
281
def __init__(self, load_fn: Callable, batch: bool = True): ...
282
async def load(self, key: Any) -> Any: ...
283
async def load_many(self, keys: List[Any]) -> List[Any]: ...
284
285
class Upload:
286
filename: str
287
content_type: str
288
289
def create_type(name: str, fields: Dict[str, Any]) -> Type: ...
290
def merge_types(name: str, types: List[Type]) -> Type: ...
291
```
292
293
[Data Loading and Utilities](./utilities.md)
294
295
### Experimental Features
296
297
Experimental features including Pydantic integration and preview functionality that may change in future versions.
298
299
```python { .api }
300
# Pydantic integration
301
def pydantic.type(model: BaseModel) -> Any: ...
302
def pydantic.input(model: BaseModel) -> Any: ...
303
def pydantic.interface(model: BaseModel) -> Any: ...
304
```
305
306
[Experimental Features](./experimental.md)