NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
PyPI, #1553 most downloaded on PyPI
A library for creating GraphQL APIs
Latest stable
0.341.2
Last release 6 days ago
07 Nov 2026
Ships fairly regularly
a new release about every 1 weeks
Nearly every release is documented
notes for 60 of the last 60 stable releases
Nothing withdrawn
no release was ever pulled
8 years old
1155 releases · first in 2019
Drag across the ruler to compare, or tap a release to open it.
This release adds an on_stream_result hook to SchemaExtension for extension authors who need to inspect or mutate GraphQL results before they reach a
This release adds an on_stream_result hook to SchemaExtension for extension
authors who need to inspect or mutate GraphQL results before they reach a
streaming transport.
The hook wraps subscription events and queries or mutations sent over WebSockets,
SSE, or multipart responses. On transports that support experimental incremental
execution, it also wraps each incremental-delivery frame.
Strawberry's built-in MaskErrors extension now uses the hook so streamed query,
mutation, subscription, incremental-delivery, and pre-execution errors are masked
before being sent to clients.
This release was contributed by @Ladol in #4330
Additional contributors: @pre-commit-ci[bot], @patrick91
This release fixes a bug in Relay connection pagination where combining first with before returned the wrong slice of items — walking backward from th
Your coding agent can read these notes before it upgrades. Set up the MCP server →
This release fixes a bug in Relay connection pagination where combining first with before returned the wrong slice of items — walking backward from the before cursor instead of taking the first first items among those before it, per the Relay Cursor Connections spec.
This release fixes the built-in UUID , Date , DateTime , and Time scalars to reject non-string variable values with a standard coercion error instead
This release fixes the built-in UUID, Date, DateTime, and Time scalars
to reject non-string variable values with a standard coercion error instead of
raising an unhandled AttributeError/TypeError inside the parser.
Previously a value like {"id": 469610.0} sent into a UUID position crashed
with 'float' object has no attribute 'replace' and surfaced in error
trackers as a server-side exception. The Decimal scalar keeps accepting
numeric input by stringifying it, as before.
This release was contributed by @simonline in #4525
This release adds a cleaner extension API by removing the deprecated Extension import alias from strawberry.extensions . The alias was deprecated in 0…
This release adds a cleaner extension API by removing the deprecated Extension
import alias from strawberry.extensions. The alias was deprecated in
0.160.0;
import SchemaExtension instead.
Before (deprecated):
from strawberry.extensions import Extension
class MyExtension(Extension): ...After:
from strawberry.extensions import SchemaExtension
class MyExtension(SchemaExtension): ...This release was contributed by @Ckk3 in #4210
Additional contributors: @patrick91, @github-actions[bot]
This release adds precise type annotations for custom scalars: serialize , parse_value and parse_literal are now typed with graphql-core's GraphQLScal
This release adds precise type annotations for custom scalars: serialize,
parse_value and parse_literal are now typed with graphql-core's
GraphQLScalarSerializer, GraphQLScalarValueParser and
GraphQLScalarLiteralParser aliases instead of bare Callable, so
strawberry.scalar(...) calls type-check cleanly under strict type checkers.
This release was contributed by @Flamefork in #4527
This release adds configurable exception handlers that map Python exceptions to typed GraphQL union results.
This release adds configurable exception handlers that map Python exceptions to
typed GraphQL union results.
Most applications do not need to adopt this directly. It is primarily useful for
integrations and framework-level helpers: for example, catching validation
exceptions from a library such as Pydantic and exposing them as an explicit
GraphQL error type, without requiring every resolver to catch and convert those
exceptions manually.
Handlers are passed to strawberry.Schema (and strawberry.federation.Schema):
import strawberry
from strawberry.types.field import StrawberryField
class ValidationProblem(Exception):
pass
@strawberry.type
class ValidationError:
message: str
class ValidationErrorHandler(
strawberry.ExceptionHandler[ValidationProblem, ValidationError]
):
def handle(
self,
exception: ValidationProblem,
*,
field: StrawberryField,
info: strawberry.Info,
) -> ValidationError:
return ValidationError(message=str(exception))
schema = strawberry.Schema(
query=Query,
mutation=Mutation,
exception_handlers=[ValidationErrorHandler()],
)Handlers can alternatively declare exception_type and error_type class
attributes instead of type parameters, which also covers types that are only
known at runtime. Declaring both a type parameter and a conflicting attribute
for the same slot raises an error at schema creation.
Strawberry only converts the exception when the field return type includes the
handler's GraphQL error type. Other fields continue to raise normal GraphQL
errors, so applications can opt in one field at a time. Exceptions raised by
the resolver, during argument conversion, or by field extensions are all
covered.
Exception handlers apply to query and mutation fields. Subscriptions are not
covered: exceptions raised while establishing a subscription are not converted
into union results.
This release was contributed by @patrick91 in #4492
This release fixes a PyCharm false positive where classes decorated with @strawberry.type and @strawberry.input reported "Unexpected argument" on thei
This release fixes a PyCharm false positive where classes decorated with @strawberry.type and @strawberry.input reported "Unexpected argument" on their generated keyword constructors.
This release was contributed by @Speedy1991 in #4508
Additional contributors: @github-actions[bot], @patrick91
This release fixes InputMutationExtension to unpack its generated input object into the resolver's individual keyword arguments before permission clas
This release fixes InputMutationExtension to unpack its generated input
object into the resolver's individual keyword arguments before permission
classes and other field extensions run.
Previously, permission classes and field extensions on an input-mutation field
received the wrapping input object; they now receive the individual arguments
(for example name and color).
import strawberry
from strawberry.field_extensions import InputMutationExtension
from strawberry.permission import BasePermission
class IsAuthenticated(BasePermission):
message = "Not authenticated"
def has_permission(self, source, info, **kwargs) -> bool:
# Previously: kwargs == {"input": CreateFruitInput(name=..., color=...)}
# Now: kwargs == {"name": ..., "color": ...}
return True
@strawberry.type
class Mutation:
@strawberry.mutation(
extensions=[InputMutationExtension()],
permission_classes=[IsAuthenticated],
)
def create_fruit(self, name: str, color: str) -> Fruit:
return Fruit(name=name, color=color)
This release was contributed by @patrick91 in https://github.com/strawberry-graphql/strawberry/pull/4510
Additional contributors: @github-actions[bot]
This release fixes a bug where print_schema would emit a type definition twice when the same type (for example an enum) was referenced both as a schem
This release fixes a bug where print_schema would emit a type definition
twice when the same type (for example an enum) was referenced both as a schema
directive field and elsewhere in the schema. The duplicated definition produced
invalid SDL that violates the GraphQL spec and is rejected by graphql-core's
build_schema.
For example, the following schema now prints enum Role only once:
import enum
import strawberry
from strawberry.schema_directive import Location
@strawberry.enum
class Role(enum.Enum):
EDITOR = "editor"
VIEWER = "viewer"
@strawberry.schema_directive(locations=[Location.FIELD_DEFINITION])
class RequiresRole:
roles: list[Role]
@strawberry.type
class Query:
secret: str = strawberry.field(directives=[RequiresRole(roles=[Role.EDITOR])])
@strawberry.field
def assign(self, role: Role) -> bool:
return True
This release was contributed by @patrick91 in https://github.com/strawberry-graphql/strawberry/pull/4504
This release fixes a bug in the Datadog extension where spans could be left open indefinitely when a GraphQL operation raised an exception.
This release fixes a bug in the Datadog extension where spans could be left open indefinitely when a GraphQL operation raised an exception.
Strawberry now makes sure that the Datadog extension always closes spans, also in the case of exceptions.
This release was contributed by @tsauerwein in https://github.com/strawberry-graphql/strawberry/pull/4498
Additional contributors: @github-actions[bot], @patrick91
Breaking change: multipart subscriptions are now opt-in. Streaming transports are selected from subscription_protocols, so multipart subscriptions — p…
This release adds support for GraphQL subscriptions over Server-Sent Events (SSE), following the GraphQL over SSE protocol in "distinct connections mode".
SSE is opt-in. Enable it by including GRAPHQL_SSE_PROTOCOL in your
integration's subscription_protocols:
from strawberry.asgi import GraphQL
from strawberry.subscriptions import (
GRAPHQL_SSE_PROTOCOL,
GRAPHQL_TRANSPORT_WS_PROTOCOL,
GRAPHQL_WS_PROTOCOL,
)
app = GraphQL(
schema,
subscription_protocols=[
GRAPHQL_TRANSPORT_WS_PROTOCOL,
GRAPHQL_WS_PROTOCOL,
GRAPHQL_SSE_PROTOCOL,
],
)
Clients request a stream with Accept: text/event-stream. Queries, mutations,
subscriptions, and @defer/@stream are all supported on the async
streaming-capable integrations (ASGI, FastAPI, AIOHTTP, Litestar, Quart, Sanic,
async Django, and async Channels). See the
SSE subscriptions docs
for client setup, reconnection, and deployment notes (prefer HTTP/2).
Breaking change: multipart subscriptions are now opt-in. Streaming
transports are selected from subscription_protocols, so multipart
subscriptions — previously served for any Accept: multipart/mixed request —
now require MULTIPART_SUBSCRIPTION_PROTOCOL to be listed there explicitly.
This release was contributed by @patrick91 in https://github.com/strawberry-graphql/strawberry/pull/4466
This release adds Schema.stream(...), a shared execution API for custom streaming integrations.
This release adds Schema.stream(...), a shared execution API for custom
streaming integrations.
Schema.stream(...) accepts queries, mutations and subscriptions and always
returns an async sequence of results: a single ExecutionResult for queries and
mutations, and the stream of results for subscriptions. This lets streaming
transports use one schema entry point instead of choosing between execute and
subscribe themselves.
Incremental delivery operations (@defer/@stream) are also supported: their
initial result is yielded first, followed by each raw graphql-core patch frame,
which the transport is responsible for formatting.
The schema execution APIs accept either a string or an already-parsed
DocumentNode, so a transport that parsed the document itself (for example to
inspect the operation type before executing) can pass the node to avoid parsing
it again.
Strawberry's multipart HTTP transport and graphql-transport-ws handler now use
this path internally.
HTTP multipart response framing now lives in the stream transport layer instead
of AsyncBaseHTTPView.encode_multipart_data. Integrations that customized that
view method should customize the transport encoding instead.
This release was contributed by @patrick91 in https://github.com/strawberry-graphql/strawberry/pull/4460
This release fixes compatibility with graphql-core 3.3 release candidates.
This release fixes compatibility with graphql-core 3.3 release candidates.
Strawberry now handles graphql-core's renamed custom executor hook and nullable
AST argument and directive collections, so schemas using custom execution
contexts and Info.selected_fields continue to work when testing against
graphql-core 3.3.
This release was contributed by @patrick91 in https://github.com/strawberry-graphql/strawberry/pull/4470
This release adds a shared internal HTTP stream transport for multipart subscription responses.
This release adds a shared internal HTTP stream transport for multipart subscription responses.
Application behavior for multipart subscriptions is largely unchanged. The shared transport now owns multipart response headers, heartbeat frames, completion frames, batching errors, and sync-mode errors, keeping Strawberry's built-in HTTP integrations on the same streaming contract.
The one behavioral change is that each multipart part's Content-Length is now
computed from the UTF-8 byte length of the payload instead of its character
count, fixing the header for responses containing non-ASCII data.
This release was contributed by @patrick91 in https://github.com/strawberry-graphql/strawberry/pull/4469
This release fixes schema printing for input object defaults that explicitly set nullable fields to null.
This release fixes schema printing for input object defaults that explicitly set
nullable fields to null.
Strawberry now preserves explicit None values in printed nested input
defaults, including fields set with strawberry.Some(None) and fields renamed
with strawberry.field(name=...), while still omitting fields that were not
explicitly set.
This release was contributed by @patrick91 in https://github.com/strawberry-graphql/strawberry/pull/4461
Previously attributes which were not camelCase would be removed from field arguments for queries: ```python import strawberry
Previously attributes which were not camelCase would be removed from field arguments for queries:
import strawberry
@strawberry.input
class Bar:
a: str
b: str
some_values: list[str] | None = None
@strawberry.input(one_of=True)
class Foo:
bar: strawberry.Maybe[Bar]
c: strawberry.Maybe[str]
@strawberry.type
class Query:
@strawberry.field
async def foobar(
self,
info: strawberry.Info,
foo: Foo = Foo(
bar=strawberry.Some(Bar(a="hi", b="bye", some_values=["my", "world"])),
c=None,
),
) -> str: ...
schema = strawberry.Schema(Query)
Once printed the output would look like the following with the some_values removed.
directive @oneOf on INPUT_OBJECT
input Bar {
a: String!
b: String!
someValues: [String!] = null
}
input Foo @oneOf {
bar: Bar
c: String
}
type Query {
foobar(foo: Foo! = {bar: {a: "hi", b: "bye"}}): String!
}
After this fix, the value will be reflected in the print statement:
directive @oneOf on INPUT_OBJECT
input Bar {
a: String!
b: String!
someValues: [String!] = null
}
input Foo @oneOf {
bar: Bar
c: String
}
type Query {
foobar(foo: Foo! = {bar: {a: "hi", b: "bye", someValues: ["my", "world"]}}): String!
}
This release was contributed by @plyte in https://github.com/strawberry-graphql/strawberry/pull/4391
Additional contributors: @pre-commit-ci[bot]
scalar_overrides now matches generic dict annotations by their origin as a fallback, so registering a bare dict covers every dict[K, V] parameterizati
scalar_overrides now matches generic dict annotations by their origin as a
fallback, so registering a bare dict covers every dict[K, V]
parameterization instead of needing one entry per variant.
Before, registering only the unparameterized origin (dict) did not match
parameterized annotations like dict[str, int]. You had to register the exact
annotation, and any other shape such as dict[str, list[int]] raised
Unexpected type:
from typing import Any
import strawberry
from strawberry.scalars import JSON
@strawberry.type
class Query:
settings: dict[str, Any]
metadata: dict[str, list[int]]
schema = strawberry.Schema(
query=Query,
scalar_overrides={dict[str, Any]: JSON},
)
Now registering the unparameterized dict covers all of its parameterizations,
including resolver and mutation arguments typed with dict[...]. This is
especially useful for strawberry.experimental.pydantic models with typed
dictionary fields. Lookup still tries an exact match first, so existing overrides
keep working unchanged.
This release was contributed by @Vansh-Sharma27 in https://github.com/strawberry-graphql/strawberry/pull/4440
Additional contributors: @pre-commit-ci[bot]
Passing an instance is now deprecated. extensions no longer accepts SchemaExtension instances in the type signature, so mypy and pyright will flag exi…
Schema(extensions=...) now accepts a class or a zero-arg factory and
builds a fresh extension per request. This fixes a race where shared
instances leaked ExecutionContext across concurrent requests, which
also produced mixed traces in ApolloTracingExtension,
ApolloFederationTracingExtension, DatadogTracingExtension, and
OpenTelemetryExtension.
schema = strawberry.Schema(
Query,
extensions=[
MaxTokensLimiter,
lambda: MyExtension(arg=...),
],
)
Passing an instance is now deprecated. extensions no longer accepts
SchemaExtension instances in the type signature, so mypy and pyright
will flag existing call sites. Instances still work at runtime for
backwards compatibility, but the same object is reused for every
request, so concurrent requests can see each other's
ExecutionContext. Switch to the class or a factory for per-request
isolation and to silence the warning.
This release was contributed by @bellini666 in https://github.com/strawberry-graphql/strawberry/pull/4392
This release fixes validation of fragment spreads in QueryDepthLimiter and MaxAliasesLimiter.
This release fixes validation of fragment spreads in QueryDepthLimiter and
MaxAliasesLimiter.
QueryDepthLimiter now tracks visited fragments while calculating operation depth,
preventing circular fragment references from causing unbounded recursion.
MaxAliasesLimiter now expands fragment spreads when counting aliases, so aliases
declared inside fragments are counted each time the fragment is used.
This release was contributed by @patrick91 in https://github.com/strawberry-graphql/strawberry/pull/4421
Fixes these two CVEs:
Fix UnresolvedFieldTypeError when using from __future__ import annotations together with a module-level Annotated[..., strawberry.lazy(...)] alias. Th
Fix UnresolvedFieldTypeError when using from __future__ import annotations together with a module-level Annotated[..., strawberry.lazy(...)] alias. The aliased form now resolves the same as inlining Annotated[...] on the field.
from __future__ import annotations
from typing import TYPE_CHECKING, Annotated
import strawberry
if TYPE_CHECKING:
from .user import User
LazyUser = Annotated["User", strawberry.lazy(".user")]
@strawberry.type
class Post:
user: LazyUser # previously failed
Contributed by @bellini666 in #4415
The types.field.resolver.ReservedParameterSpecification protocol now requires classes to have __hash__ as well, because instances of those classes are
The types.field.resolver.ReservedParameterSpecification protocol now requires classes to have __hash__ as well,
because instances of those classes are to be used as dictionary keys.
This release was contributed by @jonathandung in https://github.com/strawberry-graphql/strawberry/pull/4411
Additional contributors: @pre-commit-ci[bot]
This release fixes an issue in the bundled GraphiQL template where editing HTTP headers, including Authorization headers, wrote those values into the
This release fixes an issue in the bundled GraphiQL template where editing HTTP
headers, including Authorization headers, wrote those values into the browser
URL.
GraphiQL still supports loading headers from existing headers URL parameters,
but newly edited headers are no longer added to the URL. Query and variables URL
sharing is unchanged.
This release was contributed by @patrick91 in https://github.com/strawberry-graphql/strawberry/pull/4409
This release fixes the Channels integration when using cross-web 0.6.0 or newer.
This release fixes the Channels integration when using cross-web 0.6.0 or newer.
cross-web now requires request adapters to expose path_params, so Strawberry's
Channels HTTP adapters now read them from the Channels url_route scope.
This release was contributed by @patrick91 in https://github.com/strawberry-graphql/strawberry/pull/4390
Await cancelled subscription tasks during WebSocket shutdown so their finally blocks run before shared state (DB pools, event loop) is torn down.
Await cancelled subscription tasks during WebSocket shutdown so their finally blocks run before shared state (DB pools, event loop) is torn down.
This release was contributed by @Flamefork in https://github.com/strawberry-graphql/strawberry/pull/4319
Raise MissingFieldAnnotationError instead of MissingReturnAnnotationError when a field using strawberry.field(resolver=...) is missing both a type ann
Raise MissingFieldAnnotationError instead of MissingReturnAnnotationError when a field using strawberry.field(resolver=...) is missing both a type annotation and a resolver return type.
This release was contributed by @youngjaekwon in https://github.com/strawberry-graphql/strawberry/pull/4360
Additional contributors: @pre-commit-ci[bot]
Cancel DataLoader dispatch task when all futures are cancelled.
Cancel DataLoader dispatch task when all futures are cancelled.
Previously, the background task created by dispatch() was fire-and-forget — its
reference was never stored, so it couldn't be cancelled even when no caller was
waiting for the results. This caused wasted work (e.g. database queries against
closed sessions) when using asyncio.TaskGroup or similar structured concurrency
patterns that cancel futures on failure.
The dispatch task is now tracked in Batch._dispatch_task and automatically
cancelled when all futures in the batch are cancelled.
This release was contributed by @ChihebBENCHEIKH1 in https://github.com/strawberry-graphql/strawberry/pull/4379
Fix deprecation_reason not being copied from arguments to auto-generated input type fields in InputMutationExtension.
Fix deprecation_reason not being copied from arguments to auto-generated input type fields in InputMutationExtension.
This release was contributed by @youngjaekwon in https://github.com/strawberry-graphql/strawberry/pull/4353
This release fixes a bug in _listen_to_channel_generator where yield await awaitable inside try/except asyncio.TimeoutError caused the yield to fall w
This release fixes a bug in _listen_to_channel_generator where yield await awaitable inside try/except asyncio.TimeoutError caused the yield to fall
within the try block's bytecode exception table range.
This meant that a TimeoutError thrown into the generator at the yield point
(i.e. when the generator is suspended after delivering a value) was incorrectly
caught by the internal timeout handler, silently stopping the generator instead
of propagating to the caller. In production, this could manifest as
RuntimeError: cannot reuse already awaited coroutine during WebSocket
disconnect cleanup.
The fix splits yield await awaitable into result = await awaitable followed
by yield result, so the yield is outside the try block and exceptions
thrown at the yield point propagate correctly.
This release was contributed by @ben-xo in https://github.com/strawberry-graphql/strawberry/pull/4352
This release attaches error details to Apollo Federation inline tracing (FTV1) trace nodes. This was missing in the original FTV1 addition made in 0.3
This release attaches error details to Apollo Federation inline tracing (FTV1) trace nodes. This was missing in the original FTV1 addition made in 0.314.0.
When a resolver raises an exception, the error message, location, and path are now included in the corresponding trace node, allowing Apollo Studio to display error information alongside timing data.
This release was contributed by @FineAndDanD in https://github.com/strawberry-graphql/strawberry/pull/4351
Additional contributors: @bellini666
This release adds support for Apollo Federation inline tracing (FTV1).
This release adds support for Apollo Federation inline tracing (FTV1).
When a request includes the apollo-federation-include-trace: ftv1 header, Strawberry now records per-resolver timing information and includes it in the response under extensions.ftv1 as a base64-encoded protobuf message, following the Apollo Federation trace format. This allows an Apollo Gateway to aggregate subgraph traces and report them to Apollo Studio.
Install the new optional extra to pull in the required protobuf dependency:
pip install 'strawberry-graphql[apollo-federation]'
Use the async extension for async schemas:
import strawberry
from strawberry.extensions.tracing import ApolloFederationTracingExtension
@strawberry.type
class Query:
@strawberry.field
def hello(self) -> str:
return "Hello, world!"
schema = strawberry.Schema(
query=Query,
extensions=[ApolloFederationTracingExtension],
)
Or the sync version when running outside of an async context:
from strawberry.extensions.tracing import ApolloFederationTracingExtensionSync
schema = strawberry.Schema(
query=Query,
extensions=[ApolloFederationTracingExtensionSync],
)
Security: any client can send the
apollo-federation-include-trace: ftv1header unless you restrict it. Tracing payloads expose resolver timing details, so make sure only a trusted Apollo Gateway (or other internal traffic) can request traces — for example by enforcing authentication, network policy, or stripping the header from public requests at the edge.\
Release contributed by @bellini666 via #4136
Add PydanticErrorExtension to format validation errors into structured GraphQL error extensions.
Add PydanticErrorExtension to format validation errors into structured GraphQL error extensions.
Includes:
Releases contributed by @peehu-k via #4342
Add PydanticErrorExtension to format validation errors into structured GraphQL error extensions.
Includes:
Contributed by Peehu Kandwal via PR #4342
Fix a memory leak in the graphql-transport-ws WebSocket handler where completed task objects would accumulate in a list between messages. Task cleanup
Fix a memory leak in the graphql-transport-ws WebSocket handler where completed
task objects would accumulate in a list between messages. Task cleanup now uses
asyncio.Task.add_done_callback for immediate cleanup instead of deferred reaping.
Releases contributed by @bellini666 via #4345
Fix a memory leak in the graphql-transport-ws WebSocket handler where completed
task objects would accumulate in a list between messages. Task cleanup now uses
asyncio.Task.add_done_callback for immediate cleanup instead of deferred reaping.
Contributed by Thiago Bellini Ribeiro via PR #4345
This release fixes two security vulnerabilities in the WebSocket subscription handlers (CVE-2026-35526, CVE-2026-35523).
This release fixes two security vulnerabilities in the WebSocket subscription handlers (CVE-2026-35526, CVE-2026-35523).
CVE-2026-35526 - Authentication bypass in graphql-ws: The legacy
graphql-ws protocol handler didn't verify that the connection_init
handshake was completed before accepting start messages, allowing clients
to bypass any authentication logic in on_ws_connect. The connection is now
closed with 4401 Unauthorized if the handshake hasn't been completed.
CVE-2026-35523 - Unbounded subscriptions per connection: Both WebSocket
protocol handlers allowed unlimited concurrent subscriptions on a single
connection, making it possible for a malicious client to exhaust server
resources. A new max_subscriptions_per_connection parameter has been added
to all views (default: 100). Set it to None to disable the limit.
Example:
import strawberry
from strawberry.fastapi import GraphQLRouter
schema = strawberry.Schema(query=Query, subscription=Subscription)
# default is 100, set to None to disable the limit
graphql_app = GraphQLRouter(schema, max_subscriptions_per_connection=50)
Releases contributed by @patrick91 via #4344
Fix compatibility with Starlette 1.0.0 in the dev server by replacing removed add_route/add_websocket_route methods with Route/WebSocketRoute objects
Fix compatibility with Starlette 1.0.0 in the dev server by replacing
removed add_route/add_websocket_route methods with Route/WebSocketRoute
objects passed to the Starlette constructor.
Releases contributed by @bellini666 via #4328
Fix compatibility with Starlette 1.0.0 in the dev server by replacing
removed add_route/add_websocket_route methods with Route/WebSocketRoute
objects passed to the Starlette constructor.
Contributed by Thiago Bellini Ribeiro via PR #4328
Fix Annotated metadata being lost on optional union types
Fix Annotated metadata being lost on optional union types
When using Annotated[A | B | None, strawberry.union("MyUnion")],
the custom union name and other metadata would be dropped during None stripping, causing the schema to fall back to an auto-generated name
(e.g. "AB" instead of "MyUnion").
Releases contributed by @GabrielTDS-dev via #4321
Fix Annotated metadata being lost on optional union types
When using Annotated[A | B | None, strawberry.union("MyUnion")],
the custom union name and other metadata would be dropped during None stripping, causing the schema to fall back to an auto-generated name
(e.g. "AB" instead of "MyUnion").
Contributed by GabrielTDS-dev via PR #4321
strawberry.asdict now recursively unwraps Some() container values and removes keys with the UNSET value.
strawberry.asdict now recursively unwraps Some() container values and removes keys with the UNSET value.
Releases contributed by @GriceTurrble via #4320
strawberry.asdict now recursively unwraps Some() container values and removes keys with the UNSET value.
Contributed by Galen Rice via PR #4320
Fix UnallowedReturnTypeForUnion when using a generic type with a union TypeVar (e.g. Collection[A | B]) inside an outer union (Collection[A | B] | Err
Fix UnallowedReturnTypeForUnion when using a generic type with a union
TypeVar (e.g. Collection[A | B]) inside an outer union
(Collection[A | B] | Error).
Releases contributed by @bellini666 via #4302
Fix UnallowedReturnTypeForUnion when using a generic type with a union
TypeVar (e.g. Collection[A | B]) inside an outer union
(Collection[A | B] | Error).
Contributed by Thiago Bellini Ribeiro via PR #4302
Fix TypeError: unhashable type: 'EnumAnnotation' when using Annotated enums as resolver parameter types (e.g., Annotated[Color, strawberry.enum()]).
Fix TypeError: unhashable type: 'EnumAnnotation' when using Annotated enums as resolver parameter types (e.g., Annotated[Color, strawberry.enum()]).
Releases contributed by @bellini666 via #4305
Fix TypeError: unhashable type: 'EnumAnnotation' when using Annotated enums as resolver parameter types (e.g., Annotated[Color, strawberry.enum()]).
Contributed by Thiago Bellini Ribeiro via PR #4305
This release fixes an InvalidStateError crash in the DataLoader when a batch load function raises an exception and some futures in the batch have alre
This release fixes an InvalidStateError crash in the DataLoader when a batch
load function raises an exception and some futures in the batch have already been
cancelled (e.g. due to client disconnection).
The error handler in dispatch_batch now skips cancelled futures before calling
set_exception, matching the guard that already exists in the success path
(added in #2339).
Releases contributed by @ben-xo via #4300
Enums can now be registered via Annotated. The preferred way is still using @strawberry.enum as a decorator, but when you need to expose an existing e
Enums can now be registered via Annotated. The preferred way is still using
@strawberry.enum as a decorator, but when you need to expose an existing enum
under a different name or alias, Annotated works as a proper type alias in all
type checkers:
from typing import Annotated
from enum import Enum
import strawberry
class IceCreamFlavour(Enum):
VANILLA = "vanilla"
STRAWBERRY = "strawberry"
CHOCOLATE = "chocolate"
MyIceCreamFlavour = Annotated[
IceCreamFlavour, strawberry.enum(description="Ice cream flavours")
]
@strawberry.type
class Query:
@strawberry.field
def flavour(self) -> MyIceCreamFlavour:
return IceCreamFlavour.VANILLA
Releases contributed by @bellini666 via #4293
The strawberry mypy plugin has been restored with minimal support for strawberry.experimental.pydantic types. If you use pydantic integration, add the
The strawberry mypy plugin has been restored with minimal support for
strawberry.experimental.pydantic types. If you use pydantic integration,
add the plugin to your mypy configuration:
[mypy]
plugins = pydantic.mypy, strawberry.ext.mypy_plugin
Releases contributed by @bellini666 via #4292
The strawberry mypy plugin has been restored with minimal support for
strawberry.experimental.pydantic types. If you use pydantic integration,
add the plugin to your mypy configuration:
[mypy]
plugins = pydantic.mypy, strawberry.ext.mypy_plugin
Contributed by Thiago Bellini Ribeiro via PR #4292
Fix sync execution crash with graphql-core 3.3 where execute_sync() would return a coroutine instead of an ExecutionResult, causing RuntimeError: Ther
Fix sync execution crash with graphql-core 3.3 where execute_sync() would return a coroutine
instead of an ExecutionResult, causing RuntimeError: There is no current event loop,
because graphql-core 3.3's is_async_iterable default treats objects with __aiter__
(like Django QuerySets) as async iterables.
Now passes is_async_iterable=lambda _x: False during sync execution to prevent this.
Note: graphql-core >= 3.3.0a12 is now the minimum required version for the 3.3.x series.
Releases contributed by @bellini666 via #4267
Fix two NameError issues in schema-codegen output when types are referenced before they are defined.
Fix two NameError issues in schema-codegen output when types are referenced before they are defined.
First, forward references in field annotations (e.g. foo: Foo appearing before Foo is defined) are now handled by emitting from __future__ import annotations at the top of the generated file. Per PEP 563, this stores all annotations as strings instead of evaluating them at class definition time, so the referenced names don't need to exist yet.
Second, union definitions like FooOrBar = Annotated[Foo | Bar, strawberry.union(...)] are runtime expressions that from __future__ import annotations cannot defer. These are now correctly ordered by declaring union member types as dependencies, so unions are always emitted after their members.
Changes:
from __future__ import annotations in generated code to handle forward references in field annotations.Releases contributed by @sanlil via #4192
Add query property to Info class, allowing resolvers to access the full GraphQL document string sent in the request via info.query.
Add query property to Info class, allowing resolvers to access the full GraphQL document string sent in the request via info.query.
Example usage:
import strawberry
@strawberry.type
class Query:
@strawberry.field
def hello(self, info: strawberry.Info, name: str) -> str:
print(info.query)
return f"Hello {name}"
When executing this query:
query Hello($name: String!) {
hello(name: $name)
}
info.query returns the full query string:
"query Hello($name: String!) {\n hello(name: $name)\n}"
Releases contributed by @Ckk3 via #4289
Fix compatibility with Python 3.14 when using the Pydantic integration with Pydantic V2. Previously, importing strawberry.experimental.pydantic on Pyt
Fix compatibility with Python 3.14 when using the Pydantic integration with Pydantic V2. Previously, importing strawberry.experimental.pydantic on Python 3.14 would trigger:
UserWarning: Core Pydantic V1 functionality isn't compatible with Python 3.14 or greater.
This is now fixed by avoiding pydantic.v1 imports on Python 3.14+.
Releases contributed by @zshuzh via #4283
Fix from __future__ import annotations breaking lazy types inside generic wrappers like Optional[], tuple[], dict[], Sequence[], etc. Previously only
Fix from __future__ import annotations breaking lazy types inside generic wrappers like Optional[], tuple[], dict[], Sequence[], etc. Previously only Union[], list[]/List[], and Annotated[] were handled during AST namespace resolution, causing _eval_type to fail when lazy types were nested inside other generic subscripts.
Releases contributed by @bellini666 via #4270
Fix from __future__ import annotations breaking lazy types inside generic wrappers like Optional[], tuple[], dict[], Sequence[], etc. Previously only Union[], list[]/List[], and Annotated[] were handled during AST namespace resolution, causing _eval_type to fail when lazy types were nested inside other generic subscripts.
Contributed by Thiago Bellini Ribeiro via PR #4270
Fix ApolloTracingExtension crashing with AttributeError when executing invalid queries (e.g., { node() }). All timing attributes are now initialized i
Fix ApolloTracingExtension crashing with AttributeError when executing invalid queries (e.g., { node() }). All timing attributes are now initialized in __init__ and lifecycle hooks use try/finally to ensure proper cleanup.
Releases contributed by @Br1an67 via #4271
Fix ApolloTracingExtension crashing with AttributeError when executing invalid queries (e.g., { node() }). All timing attributes are now initialized in __init__ and lifecycle hooks use try/finally to ensure proper cleanup.
…name")] age: Annotated[int, strawberry.field(deprecation_reason="Use birthDate instead")]
This release adds support for defining fields using the Annotated syntax. This provides an
alternative way to specify field metadata alongside the type annotation.
Example usage:
from typing import Annotated
import strawberry
@strawberry.type
class Query:
name: Annotated[str, strawberry.field(description="The name")]
age: Annotated[int, strawberry.field(deprecation_reason="Use birthDate instead")]
@strawberry.input
class CreateUserInput:
name: Annotated[str, strawberry.field(description="User's name")]
email: Annotated[str, strawberry.field(description="User's email")]
This syntax works alongside the existing assignment syntax:
@strawberry.type
class Query:
# Both styles work
field1: Annotated[str, strawberry.field(description="Using Annotated")]
field2: str = strawberry.field(description="Using assignment")
All strawberry.field() options are supported including description, name,
deprecation_reason, directives, metadata, and permission_classes.
Releases contributed by @patrick91 via #4059
This release fixes issues with explicit field definitions in experimental pydantic types:
This release fixes issues with explicit field definitions in experimental pydantic types:
all_fields=True now respects explicit field definitions: Previously, using all_fields=True would override any explicitly defined fields in the strawberry type. Now, explicit definitions take precedence, allowing you to:
strawberry.Private to hide them from the GraphQL schemaThe warning "Using all_fields overrides any explicitly defined fields" has been removed since combining all_fields=True with explicit definitions is now a valid and useful pattern.
Private fields are auto-populated from pydantic models: When a strawberry.Private field has the same name as a pydantic model field, from_pydantic() will automatically populate it from the model (can be overridden via the extra dict).
Example:
from pydantic import BaseModel
import strawberry
from strawberry.experimental.pydantic import type as pyd_type
from strawberry.extensions.field_extension import FieldExtension
class MaskExtension(FieldExtension):
def resolve(self, next_, source, info, **kwargs):
result = next_(source, info, **kwargs)
return result[:3] + "****" if result else result
class UserModel(BaseModel):
name: str
email: str
password: str
@pyd_type(model=UserModel, all_fields=True)
class User:
# Add extension to mask email in responses
email: str = strawberry.field(extensions=[MaskExtension()])
# Hide password from GraphQL schema entirely
password: strawberry.Private[str]
# name and email are exposed in schema, password is not
# email will be masked by the extension
pydantic_user = UserModel(name="Alice", email="alice@example.com", password="secret")
strawberry_user = User.from_pydantic(pydantic_user)
# Private field is still accessible internally
print(strawberry_user.password) # "secret"
Releases contributed by @XChikuX via #4179
Remove deprecated _type_definition and _enum_definition aliases, deprecated since 0.187.0.
Remove deprecated _type_definition and _enum_definition aliases, deprecated since 0.187.0.
Before (deprecated):
type_def = MyType._type_definition
enum_def = MyEnum._enum_definition
After:
type_def = MyType.__strawberry_definition__
enum_def = MyEnum.__strawberry_definition__
Releases contributed by @Ckk3 via #4219
Remove deprecated _type_definition and _enum_definition aliases, deprecated since 0.187.0.
Before (deprecated):
type_def = MyType._type_definition
enum_def = MyEnum._enum_definition
After:
type_def = MyType.__strawberry_definition__
enum_def = MyEnum.__strawberry_definition__
Contributed by Luis Gustavo via PR #4219
Remove deprecated fields parameter from Pydantic decorators, deprecated since 0.82.0.
Remove deprecated fields parameter from Pydantic decorators, deprecated since 0.82.0.
Before (deprecated):
@strawberry.experimental.pydantic.type(model=UserModel, fields=["name", "age"])
class User:
pass
After:
@strawberry.experimental.pydantic.type(model=UserModel)
class User:
name: strawberry.auto
age: strawberry.auto
Releases contributed by @Ckk3 via #4223
Remove deprecated fields parameter from Pydantic decorators, deprecated since 0.82.0.
Before (deprecated):
@strawberry.experimental.pydantic.type(model=UserModel, fields=["name", "age"])
class User:
pass
After:
@strawberry.experimental.pydantic.type(model=UserModel)
class User:
name: strawberry.auto
age: strawberry.auto
Contributed by Luis Gustavo via PR #4223
Remove deprecated is_unset() function and deprecated UNSET import from strawberry.arguments, deprecated since 0.109.0.
Remove deprecated is_unset() function and deprecated UNSET import from strawberry.arguments, deprecated since 0.109.0.
Before (deprecated):
from strawberry.types.unset import is_unset
from strawberry.types.arguments import UNSET
if is_unset(value):
...
After:
from strawberry import UNSET
if value is UNSET:
...
Releases contributed by @Ckk3 via #4212
Remove deprecated is_unset() function and deprecated UNSET import from strawberry.arguments, deprecated since 0.109.0.
Before (deprecated):
from strawberry.types.unset import is_unset
from strawberry.types.arguments import UNSET
if is_unset(value):
...
After:
from strawberry import UNSET
if value is UNSET:
...
Contributed by Luis Gustavo via PR #4212
Remove deprecated LazyType["Name", "module"] syntax, deprecated since 0.129.0.
Remove deprecated LazyType["Name", "module"] syntax, deprecated since 0.129.0.
Before (deprecated):
from strawberry.lazy_type import LazyType
@strawberry.type
class Query:
user: LazyType["User", "myapp.types"]
After:
from typing import Annotated
import strawberry
@strawberry.type
class Query:
user: Annotated["User", strawberry.lazy("myapp.types")]
Releases contributed by @Ckk3 via #4218
Remove deprecated LazyType["Name", "module"] syntax, deprecated since 0.129.0.
Before (deprecated):
from strawberry.lazy_type import LazyType
@strawberry.type
class Query:
user: LazyType["User", "myapp.types"]
After:
from typing import Annotated
import strawberry
@strawberry.type
class Query:
user: Annotated["User", strawberry.lazy("myapp.types")]
Contributed by Luis Gustavo via PR #4218
Fix Annotated[Union[A, B], strawberry.union("Name")] raising TypeError when used as a type parameter in a generic subclass (e.g., class Items(Listing[
Fix Annotated[Union[A, B], strawberry.union("Name")] raising TypeError when
used as a type parameter in a generic subclass (e.g., class Items(Listing[ItemResponse])).
Fix Annotated[Union[A, B], strawberry.union("Name")] raising TypeError when
used as a type parameter in a generic subclass (e.g., class Items(Listing[ItemResponse])).
Contributed by Thiago Bellini Ribeiro via PR #4235
Add strawberry.federation.params module with shared TypedDicts (FederationFieldParams, FederationInterfaceParams, FederationTypeParams) and processing
Add strawberry.federation.params module with shared TypedDicts (FederationFieldParams, FederationInterfaceParams, FederationTypeParams) and processing functions (process_federation_field_directives, process_federation_type_directives) for federation directives.
These TypedDicts can be consumed via Unpack[...] to avoid duplicating federation parameter lists across packages. The processing functions are extracted from inline logic previously in field.py and object_type.py.
Also fixes a bug where inaccessible=False incorrectly added the Inaccessible directive on types/interfaces.
If you still have strawberry.ext.mypy_plugin in your mypy configuration, it will emit a DeprecationWarning and can be safely removed. Pydantic users o…
The strawberry mypy plugin has been removed. It is no longer needed thanks to
@dataclass_transform, overloaded signatures, and the StrawberryTypeFromPydantic
protocol.
If you still have strawberry.ext.mypy_plugin in your mypy configuration, it will
emit a DeprecationWarning and can be safely removed. Pydantic users only need
the pydantic.mypy plugin.
Releases contributed by @bellini666 via #4258
The strawberry mypy plugin has been removed. It is no longer needed thanks to
@dataclass_transform, overloaded signatures, and the StrawberryTypeFromPydantic
protocol.
If you still have strawberry.ext.mypy_plugin in your mypy configuration, it will
emit a DeprecationWarning and can be safely removed. Pydantic users only need
the pydantic.mypy plugin.
Contributed by Thiago Bellini Ribeiro via PR #4258
Remove deprecated strawberry server CLI command, deprecated since 0.283.0.
Remove deprecated strawberry server CLI command, deprecated since 0.283.0.
Before (deprecated):
strawberry server myapp:schema
After:
strawberry dev myapp:schema
Releases contributed by @Ckk3 via #4215
Remove deprecated strawberry server CLI command, deprecated since 0.283.0.
Before (deprecated):
strawberry server myapp:schema
After:
strawberry dev myapp:schema
Contributed by Luis Gustavo via PR #4215
Remove deprecated strawberry server CLI command, deprecated since 0.283.0 .
Before (deprecated):
Terminal window
strawberry server myapp:schema
After:
Terminal window
strawberry dev myapp:schema
Contributed by Luis Gustavo via PR #4215
Remove deprecated asserts_errors parameter from test clients, deprecated since 0.246.0.
Remove deprecated asserts_errors parameter from test clients, deprecated since 0.246.0.
Before (deprecated):
result = client.query(query, asserts_errors=False)
After:
result = client.query(query, assert_no_errors=False)
Releases contributed by @Ckk3 via #4217
Remove deprecated asserts_errors parameter from test clients, deprecated since 0.246.0.
Before (deprecated):
result = client.query(query, asserts_errors=False)
After:
result = client.query(query, assert_no_errors=False)
Contributed by Luis Gustavo via PR #4217
Remove deprecated debug-server extra from pyproject.toml, deprecated since 0.283.0.
Remove deprecated debug-server extra from pyproject.toml, deprecated since 0.283.0.
Before (deprecated):
pip install strawberry-graphql[debug-server]
After:
pip install strawberry-graphql[cli]
Releases contributed by @Ckk3 via #4228
Remove deprecated debug-server extra from pyproject.toml, deprecated since 0.283.0.
Before (deprecated):
pip install strawberry-graphql[debug-server]
After:
pip install strawberry-graphql[cli]
Contributed by Luis Gustavo via PR #4228
Remove deprecated debug-server extra from pyproject.toml , deprecated since 0.283.0 .
Before (deprecated):
Terminal window
pip install strawberry-graphql[debug-server]
After:
Terminal window
pip install strawberry-graphql[cli]
Contributed by Luis Gustavo via PR #4228
Fix execution_context.result being None or belonging to a wrong request when multiple async requests execute concurrently (e.g. via asyncio.gather). S
Fix execution_context.result being None or belonging to a wrong request when multiple async requests execute concurrently (e.g. via asyncio.gather). Shared cached extension instances are no longer reused across concurrent async requests.
Releases contributed by @bellini666 via #4256
Fix execution_context.result being None or belonging to a wrong request when multiple async requests execute concurrently (e.g. via asyncio.gather). Shared cached extension instances are no longer reused across concurrent async requests.
Contributed by Thiago Bellini Ribeiro via PR #4256
One column per quarter.