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.0Strawberry 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.
pip install strawberry-graphqlimport strawberryFor specific components:
from strawberry import (
type, input, interface, enum, scalar, union,
field, mutation, subscription, argument,
Schema, Info, BasePermission, ID
)import strawberry
from typing import List
@strawberry.type
class User:
id: strawberry.ID
name: str
email: str
age: int = strawberry.field(description="User's age in years")
@strawberry.field
def display_name(self) -> str:
return f"{self.name} ({self.email})"
@strawberry.type
class Query:
@strawberry.field
def users(self) -> List[User]:
return [
User(id="1", name="Alice", email="alice@example.com", age=30),
User(id="2", name="Bob", email="bob@example.com", age=25)
]
@strawberry.field
def user(self, id: strawberry.ID) -> User:
# Fetch user by ID logic here
return User(id=id, name="Alice", email="alice@example.com", age=30)
@strawberry.type
class Mutation:
@strawberry.mutation
def create_user(self, name: str, email: str, age: int) -> User:
# Create user logic here
return User(id="new", name=name, email=email, age=age)
schema = strawberry.Schema(query=Query, mutation=Mutation)
# Execute a query
result = schema.execute_sync('''
query {
users {
id
name
displayName
}
}
''')Strawberry GraphQL is built around several key architectural components:
@strawberry.type, @strawberry.field) to define GraphQL schemas directly from Python classes and functionsEssential decorators and types for defining GraphQL schemas using Python dataclasses and type annotations. These form the foundation of any Strawberry GraphQL application.
def type(cls=None, *, name: str = None, description: str = None) -> Any: ...
def input(cls=None, *, name: str = None, description: str = None) -> Any: ...
def interface(cls=None, *, name: str = None, description: str = None) -> Any: ...
def enum(cls=None, *, name: str = None, description: str = None) -> Any: ...
def scalar(cls=None, *, serialize: Callable = None, parse_value: Callable = None) -> Any: ...
def union(name: str, types: Tuple[Type, ...]) -> Any: ...Field definition system with custom resolvers, descriptions, permissions, and advanced configuration options for GraphQL fields.
def field(
resolver: Callable = None,
*,
name: str = None,
description: str = None,
deprecation_reason: str = None,
permission_classes: List[Type[BasePermission]] = None
) -> Any: ...
def mutation(
resolver: Callable = None,
*,
name: str = None,
description: str = None,
permission_classes: List[Type[BasePermission]] = None
) -> Any: ...
def subscription(
resolver: Callable = None,
*,
name: str = None,
description: str = None,
permission_classes: List[Type[BasePermission]] = None
) -> Any: ...
def argument(
name: str = None,
description: str = None,
default: Any = None
) -> Any: ...Schema creation and query execution system with support for queries, mutations, subscriptions, and context management.
class Schema:
def __init__(
self,
query: Type = None,
mutation: Type = None,
subscription: Type = None,
extensions: List[SchemaExtension] = None
): ...
def execute_sync(self, query: str, variable_values: Dict = None, context_value: Any = None) -> ExecutionResult: ...
async def execute(self, query: str, variable_values: Dict = None, context_value: Any = None) -> ExecutionResult: ...
async def subscribe(self, query: str, variable_values: Dict = None, context_value: Any = None) -> AsyncIterator: ...
class Info:
context: Any
field_name: str
operation_name: str
path: List[str]
return_type: Type
schema: Schema
variable_values: Dict[str, Any]Web framework integrations providing GraphQL endpoints for popular Python web frameworks with framework-specific features and middleware.
# FastAPI
class GraphQLRouter:
def __init__(self, schema: Schema, path: str = "/graphql"): ...
# ASGI
class GraphQL:
def __init__(
self,
schema: Schema,
graphql_ide: str = "graphiql",
allow_queries_via_get: bool = False
): ...
# Django, Flask, Sanic, etc.
class GraphQLView:
def __init__(self, schema: Schema): ...Schema and field-level extensions for adding custom functionality like validation, caching, security, and monitoring to GraphQL operations.
class SchemaExtension:
def on_request_start(self): ...
def on_request_end(self): ...
def on_validation_start(self): ...
def on_validation_end(self): ...
def on_parsing_start(self): ...
def on_parsing_end(self): ...
class FieldExtension:
def apply(self, field: StrawberryField) -> StrawberryField: ...
# Built-in extensions
class QueryDepthLimiter(SchemaExtension): ...
class ValidationCache(SchemaExtension): ...
class ParserCache(SchemaExtension): ...
class DisableIntrospection(SchemaExtension): ...Apollo Federation support for building distributed GraphQL architectures with multiple services and schema composition.
# Federation schema
class Schema:
def __init__(
self,
query: Type = None,
mutation: Type = None,
enable_federation_2: bool = False
): ...
# Federation decorators
def type(cls=None, *, keys: List[str] = None, extend: bool = False): ...
def field(resolver=None, *, external: bool = False, requires: str = None, provides: str = None): ...Complete Relay specification implementation with Node interface, connections, pagination, and global object identification.
class Node:
id: NodeID
class Connection:
edges: List[Edge]
page_info: PageInfo
class Edge:
node: Node
cursor: str
class PageInfo:
has_next_page: bool
has_previous_page: bool
start_cursor: str
end_cursor: str
def connection(resolver: Callable) -> Any: ...Utilities for efficient data loading, file uploads, type conversions, and common GraphQL patterns.
class DataLoader:
def __init__(self, load_fn: Callable, batch: bool = True): ...
async def load(self, key: Any) -> Any: ...
async def load_many(self, keys: List[Any]) -> List[Any]: ...
class Upload:
filename: str
content_type: str
def create_type(name: str, fields: Dict[str, Any]) -> Type: ...
def merge_types(name: str, types: List[Type]) -> Type: ...Experimental features including Pydantic integration and preview functionality that may change in future versions.
# Pydantic integration
def pydantic.type(model: BaseModel) -> Any: ...
def pydantic.input(model: BaseModel) -> Any: ...
def pydantic.interface(model: BaseModel) -> Any: ...