or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

core-types.mdexperimental.mdextensions.mdfederation.mdfields-resolvers.mdframework-integrations.mdindex.mdrelay.mdschema-execution.mdutilities.md
tile.json

tessl/pypi-strawberry-graphql

A library for creating GraphQL APIs using dataclasses and type annotations with extensive framework integration support.

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

To install, run

npx @tessl/cli install tessl/pypi-strawberry-graphql@0.281.0

index.mddocs/

Strawberry GraphQL

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.

Package Information

  • Package Name: strawberry-graphql
  • Package Type: pypi
  • Language: Python
  • Installation: pip install strawberry-graphql

Core Imports

import strawberry

For specific components:

from strawberry import (
    type, input, interface, enum, scalar, union,
    field, mutation, subscription, argument,
    Schema, Info, BasePermission, ID
)

Basic Usage

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
        }
    }
''')

Architecture

Strawberry GraphQL is built around several key architectural components:

  • Decorator-Based Type System: Uses Python decorators (@strawberry.type, @strawberry.field) to define GraphQL schemas directly from Python classes and functions
  • Type Safety: Leverages Python type hints and dataclasses for automatic GraphQL type generation and runtime validation
  • Schema Generation: Automatically generates GraphQL schemas from decorated Python classes, reducing boilerplate code
  • Framework Integrations: Provides dedicated integrations for popular web frameworks (FastAPI, Django, Flask, etc.) with framework-specific views and middleware
  • Extension System: Modular extension system for adding custom functionality like validation, caching, authentication, and monitoring
  • Federation Support: Built-in Apollo Federation support for microservices architectures
  • Relay Compatibility: Full Relay specification implementation for React applications

Capabilities

Core Type System

Essential 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: ...

Core Type System

Field Definitions and Resolvers

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: ...

Field Definitions

Schema and Execution

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]

Schema and Execution

Framework Integrations

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): ...

Framework Integrations

Extensions System

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): ...

Extensions System

Apollo Federation

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): ...

Apollo Federation

Relay Specification

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: ...

Relay Specification

Data Loading and Utilities

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: ...

Data Loading and Utilities

Experimental Features

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: ...

Experimental Features