Extensions, directives, and permissions
Strawberry provides extension points that add behavior around GraphQL operations, individual fields, and schema definitions. These points support request hooks, field access checks, client-facing directives, tracing, validation error reporting, and file uploads without placing all of that work in resolver functions. See Extensibility for the wider extension model.
Extension model
Schema extensions observe or change the life of a GraphQL request. Field extensions wrap one field and can also change its schema shape or its converted arguments. Strawberry creates schema extensions for each request when the schema receives an extension class or factory, so request state stays separate between concurrent requests.
The request moves through these broad stages:
flowchart LR
A[GraphQL request] --> B[Operation]
B --> C[Parse]
C --> D[Validate]
D --> E[Resolve fields]
E --> F[Response]
E --> G[Streamed results]
H[Schema extensions] -.observe.-> B
H -.observe.-> C
H -.observe.-> D
H -.observe.-> E
H -.observe.-> G
I[Field extensions] -.wrap.-> E
Use a schema extension for behavior that applies across the request. Use a field extension when the behavior belongs to selected fields, such as a permission check or a reusable result transform.
References: strawberry/…/schema.py• L256-350 strawberry/…/schema.py• L442-462 strawberry/…/base_extension.py• L16-76
Extension hook lifecycle
Lifecycle hooks run code before and after a request stage. A hook uses a generator or async generator: code before yield runs on entry and code after yield runs when the stage ends. This gives an extension one place to set up state and one place to clean it up.
| Hook | Scope | Main use |
|---|---|---|
on_operation | Whole operation | Set up request state and finish operation-wide work |
on_parse | Query parsing | Measure or control query parsing |
on_validate | Query validation | Measure or control validation |
on_execute | Field execution | Set up execution-wide state or stop an operation before field work |
on_stream_result | Each result sent by a stream | Inspect or change subscription events and incremental response frames |
resolve | Each resolver call | Wrap all field resolvers and inspect their inputs or results |
get_results | Response assembly | Add extension data to the GraphQL response extensions object |
The request execution context links these hooks to the query, variables, operation name, context, result, and other request data. An extension can use that context to share state between its entry and exit code. Async execution can await async hooks and result methods, while synchronous execution rejects async-only hooks.
Two built-in schema extensions reuse work from these stages across requests. ParserCache reuses parsed documents during on_parse, while ValidationCache reuses validation results during on_validate. Both use a bounded cache of 128 entries by default. An unbounded cache is suitable only when the set of query texts is trusted and bounded.
Hooks run in extension order on entry and unwind in the matching context-manager order on exit. A hook that changes a result can therefore affect what the transport returns, including each item from Schema.stream and each subscription event.
References: strawberry/…/base_extension.py• L23-76 strawberry/…/context.py• L34-142 strawberry/…/context.py• L161-213 strawberry/…/runner.py• L21-66 strawberry/…/parser_cache.py• L9-61 strawberry/…/validation_cache.py• L7-67
Field extension chain
Field extensions form a resolver chain around one field. Each extension can inspect or change arguments before the resolver runs, change the field during schema construction, or transform the returned value. The chain preserves the resolver contract by passing the source, request information, and compatible arguments to the next step.
The last field extension in the declared list runs first at request time. This order matters when one extension changes arguments or results that another extension consumes. An extension that only changes the field during schema construction does not need to join the resolver chain.
Field extensions may provide separate synchronous and asynchronous behavior. Async-only extensions can wrap synchronous fields, but a synchronous-only extension cannot safely wrap an async resolver. A field with mixed extensions must place all synchronous-only work before the first async-only extension.
References: strawberry/…/field_extension.py• L19-75 strawberry/…/field_extension.py• L90-182 strawberry/…/schema_converter.py• L343-365 strawberry/…/schema_converter.py• L868-1041
Directive roles
Strawberry has two directive roles. Schema directives describe schema definitions such as types and fields. Operation directives appear in a client query and can change the value returned by a field. Both roles use declared locations so GraphQL can reject a directive used in the wrong place.
Schema directives
Schema directives add metadata to the GraphQL schema and its SDL. A schema directive declares its GraphQL locations and its typed arguments. It can be attached to a schema, type, field, argument, or other supported definition. The directive itself does not change resolver behavior unless another part of the system reads its metadata.
Schema directives also connect extension behavior to the published schema. For example, a field extension can add a directive while the schema is built, and a permission can expose an automatically generated field directive. The schema converter turns these definitions into GraphQL directive definitions.
References: strawberry/schema_directive.py• L14-73 strawberry/…/schema_converter.py• L529-566 strawberry/…/field_extension.py• L19-21
Operation directives
Operation directives are defined by a function that receives the field value and any directive arguments. The schema must register the directive before a client can use it. During execution Strawberry applies custom operation directives to the resolved value in query order; the built-in @skip and @include directives remain GraphQL control directives and are not applied as value transforms.
Before the directive function runs, Strawberry coerces its arguments against the registered GraphQL directive definition and then converts them with Strawberry's argument and scalar rules. This also handles values supplied through query variables. The directive may receive Strawberry request information and the resolved field value when those inputs are part of its contract. Input object arguments also cause Strawberry to build the request information needed for their conversion.
This model lets a directive add a small, reusable result rule without creating a separate resolver for each use. Async execution awaits directive results, while the synchronous form keeps directive execution synchronous.
References: strawberry/directive.py• L62-140 strawberry/…/directives.py• L23-124 strawberry/…/schema.py• L264-265 strawberry/…/schema.py• L376-400
Resolver permissions
Permissions protect a field before its resolver runs. A permission is a BasePermission with a has_permission check. The check receives the source, Strawberry Info, and field arguments, so it can use request data from info.context and apply the same rule to sync or async resolvers.
Each permission subclass receives a stable default field schema directive when the subclass is created. Permission extensions can add these directives to the published schema, while repeated uses of the same permission class reuse its directive definition. A permission can provide its own directive metadata when the application needs a different schema description.
Permission checks must return a real boolean. Sync execution rejects an awaitable or any non-boolean result instead of treating a truthy object as approval. Async execution awaits an awaitable check and also rejects a final non-boolean result. This keeps access decisions explicit across both execution modes.
When a check fails, the permission normally raises a GraphQL error with its configured message. It can also provide a custom error class, error extensions, or an on_unauthorized method for a different failure response. Authentication remains an application concern; Strawberry supplies the context path but does not decide how a user is authenticated.
The permission system is a field extension. Multiple permissions run in their declared order, and the resolver runs only after all checks pass. Silent failure can return None or an empty list instead of an error, but only for nullable or list fields. This option hides the difference between denied access and an empty result, so use it only when that response is acceptable to clients. Async execution awaits permission results. Sync execution fails closed when a check returns an awaitable.
References: strawberry/permission.py• L39-142 strawberry/permission.py• L144-279 docs/…/permissions.md• L55-111
Tracing integrations
Tracing extensions turn GraphQL request stages and resolver work into data for an external tracing system. The built-in integrations cover Apollo tracing, Apollo Federation inline tracing, Datadog, and OpenTelemetry. Each has sync and async forms where the resolver execution model needs a distinct wrapper.
| Integration | Response or trace output | Activation or focus |
|---|---|---|
| Apollo | extensions.tracing with operation, parse, validation, and resolver timing | GraphQL response diagnostics |
| Apollo Federation | extensions.ftv1 with a base64-encoded inline trace tree | Requests that include the Apollo Federation FTV1 header |
| Datadog | Spans for operation, parse, validation, and resolver work | Datadog service traces |
| OpenTelemetry | Nested spans with GraphQL operation, field path, and filtered arguments | OpenTelemetry traces |
Tracing skips introspection and fields without a meaningful resolver. Apollo records resolver paths from the GraphQL execution path and reports operation, parse, validation, and resolver timing in the extensions.tracing response data. Its async and sync forms both finish each resolver timing record even when resolver work raises an error. Apollo Federation builds a nested resolver tree and records resolver errors in the inline trace. Its output is enabled only when the request header asks for ftv1; missing protobuf support disables that trace without changing the GraphQL response. Argument capture in OpenTelemetry can be filtered before values reach span attributes.
References: strawberry/…/apollo.py• L84-219 strawberry/…/apollo_federation.py• L289-532 strawberry/…/datadog.py• L29-183 strawberry/…/opentelemetry.py• L33-202 strawberry/…/utils.py• L14-22 strawberry/…/utils.py• L19-38
Pydantic validation errors
PydanticErrorExtension adds structured validation details to GraphQL errors caused by Pydantic model validation. It runs after the operation and leaves successful results and unrelated errors unchanged.
When Pydantic is already loaded, the extension checks each GraphQL error for an original ValidationError. It adds a validation_errors list to that error's extensions, with each item containing the dotted input field path and Pydantic's message. It does not import Pydantic when the application has not used it, so adding the extension does not make Pydantic a required dependency.
The result is an error response that keeps the normal GraphQL error while exposing field-level input feedback to clients. Applications still decide how to present these details and how to map them to form or API errors.
References: strawberry/…/pydantic_error_extension.py• L7-41 strawberry/…/__init__.py• L7-28
File upload scalar
The Upload scalar gives GraphQL mutations a typed place for multipart file values. Strawberry maps the scalar to the file object supplied by the active web integration, so the resolver receives the framework's normal upload type rather than a string or encoded value. A scalar override can make that framework type visible to type checkers and IDEs.
Multipart support follows the GraphQL multipart request specification and can replace one variable path or many nested paths with uploaded files. Integrations disable multipart uploads by default. An application must enable them at the integration boundary and address the request-forgery risks first, usually with CSRF protection.
| Use | Result |
|---|---|
One Upload variable | One file object reaches the mutation |
List of Upload values | Several files reach one mutation argument |
| Nested input containing uploads | Files are placed at their declared input paths |
The runtime file type depends on the integration, and async integrations require async resolvers. The scalar itself passes the integration value through; it does not define storage, validation, or file processing policy.
References: strawberry/…/scalars.py• L1-12 strawberry/…/scalar.py• L48-59 strawberry/…/utils.py• L6-33 docs/…/file-upload.md• L7-22 docs/…/file-upload.md• L24-69
Change checklist
When these files or sections are changed, remember to consider these:
- When changing extension hook order or sync/async support, check both
Schema.executepaths and every transport that consumes streamed results. - When changing parser or validation caching, check cache bounds and the number of distinct query texts that can reach the endpoint.
- When changing field extension application, check that schema-visible field types and argument conversion still match the resolver chain.
- When changing directive locations or names, check both the generated schema definition and the operation-time directive lookup.
- When changing directive argument coercion, check GraphQL variable values, Strawberry scalar conversion, input object conversion, and both sync and async directive execution.
- When changing permission directive creation or permission results, check shared directive identity, custom directive overrides, strict boolean checks, awaitable handling, GraphQL nullability, and the error class or error extensions exposed to clients.
- When changing Pydantic error formatting, check the optional-import path, the original GraphQL error, dotted field locations, and the
validation_errorsclient contract. - When changing a tracing output format or resolver path, check the external Apollo, Datadog, or OpenTelemetry contract and the matching sync and async extension.
- When changing Apollo Federation activation or trace encoding, check the request header, nested path tree, error data, and optional protobuf behavior.
- When changing
Upload, check the default scalar registry, integration-specific runtime types, multipart variable paths, and upload security settings.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A shared extension instance stores request state | Concurrent requests can observe another request's execution context | Pass an extension class or a factory that creates a new instance per request |
| A parser or validation cache is unbounded and receives many unique query texts | Cache memory can grow without limit | Keep the default bounded size or use maxsize=None only for trusted and bounded query sets |
| A sync-only field extension wraps an async resolver | Schema setup raises a type error or the chain cannot await safely | Implement resolve_async or place compatible extensions in a valid order |
| A permission check returns an awaitable during sync execution | Access fails closed instead of treating the awaitable as a successful check | Run the operation asynchronously or return a plain boolean from the sync check |
| A permission check returns a non-boolean value | Access is rejected instead of being decided by truthiness | Return True or False from every permission check |
fail_silently=True is used on a non-null, non-list field | Schema setup rejects the permission extension | Use a nullable or list return type when silent failure is required |
| A custom operation directive is not registered in the schema | The client cannot use the directive in a valid operation | Add the directive to the schema's directive definitions |
| A directive argument does not match its GraphQL definition or scalar rules | Argument coercion fails before the directive function runs | Keep the registered directive definition and Strawberry argument types aligned |
| A Pydantic validation error is expected before Pydantic has been used | No structured validation details are added | Load Pydantic through the application path that performs validation, or handle the normal GraphQL error |
| Apollo Federation tracing lacks the request header or protobuf support | No ftv1 trace data is returned | Send the FTV1 header and install the Apollo Federation extra |
| A tracing consumer expects a flat resolver path when the response contains list items | Resolver timings cannot be mapped to the requested field | Treat path entries as field names or list indexes from the GraphQL execution path |
| Multipart uploads are enabled without CSRF protection | A cross-site request can reach upload handling | Keep uploads disabled until the integration has a CSRF control |
Key files
| File | Why to read it |
|---|---|
| strawberry/…/schema.py | Shows how schemas register directives and create request-scoped extensions. |
| strawberry/…/base_extension.py | Defines the common lifecycle and resolver contract for schema extensions. |
| strawberry/…/context.py | Shows how sync and async hooks enter, yield, and clean up. |
| strawberry/…/parser_cache.py | Shows how parsing work is reused across requests with a bounded cache. |
| strawberry/…/validation_cache.py | Shows how validation work is reused across requests with a bounded cache. |
| strawberry/…/field_extension.py | Defines field wrapping, argument hooks, and sync/async compatibility. |
| strawberry/…/schema_converter.py | Shows where field extensions affect schema construction and resolver calls. |
| strawberry/schema_directive.py | Defines schema directive locations and typed directive metadata. |
| strawberry/directive.py | Defines client operation directives and their value and info inputs. |
| strawberry/…/directives.py | Resolves operation directives and converts their GraphQL arguments before execution. |
| strawberry/permission.py | Defines permission checks, stable schema directives, strict sync/async results, denial responses, and field integration. |
| strawberry/…/pydantic_error_extension.py | Adds optional, structured Pydantic validation details to GraphQL errors. |
| strawberry/…/apollo.py | Defines Apollo response tracing for operation stages and resolver timing. |
strawberry/extensions/tracing/ | Provides the built-in tracing adapters and their response or span models. |
| strawberry/…/utils.py | Provides the execution-path and introspection helpers used by tracing extensions. |
strawberry/file_uploads/ | Defines the Upload scalar and multipart placeholder replacement. |