Introducing a new way to review your PRs.

Read the announcement

strawberry-graphql / strawberry

A GraphQL library for Python that leverages type annotations 🍓

View on GitHub

21 documents · Updated Nov 18, 2026

docs / framework-adapters

Framework adapters

Strawberry's framework adapters expose one GraphQL transport model through the routing and request APIs of ASGI, Django, FastAPI, Flask, AIOHTTP, Channels, Chalice, Litestar, Quart, and Sanic. Each adapter connects framework request and response objects to shared HTTP or WebSocket behavior, so schema execution stays the same while routing, context creation, and response writing follow framework rules. See Web framework integration for the wider integration model and HTTP and ASGI transport for protocol behavior.

Shared transport model

The shared transport model separates GraphQL work from framework concerns. A request adapter presents method, headers, query parameters, body, form data, and path data in a common shape. The view then parses the operation, executes the schema, and gives the result to a framework-specific response builder.

The async path also treats a WebSocket as a transport with JSON messages. The framework adapter accepts the connection, selects a supported GraphQL subprotocol, and converts incoming and outgoing messages for the shared subscription handlers.

The model has two main execution forms:

  • Synchronous HTTP: A sync view reads the request and returns a normal framework response. It supports ordinary GraphQL responses and rejects streaming transports.
  • Asynchronous HTTP and WebSocket: An async view can await request data, write a stream, and run GraphQL subscriptions over WebSockets or an HTTP stream.

References: strawberry/…/base.py• L22-41 strawberry/…/async_base_view.py• L64-171 strawberry/…/sync_base_view.py• L31-63

Request lifecycle

Every adapter follows the same broad path. Framework routing chooses the GraphQL endpoint first. The adapter converts the framework request into the shared request view. The view selects HTTP or WebSocket behavior and returns a response in the framework's own form.

The request and response relationship is shown below.

flowchart LR
    A[Framework route] --> B[Framework request]
    B --> C[Request adapter]
    C --> D[Shared GraphQL view]
    D --> E[Schema execution]
    E --> F[HTTP result or stream]
    F --> G[Framework response]
    B -. WebSocket route .-> H[WebSocket adapter]
    H --> D

For HTTP, the shared view accepts GET and POST requests. It reads query parameters for GET and JSON or enabled multipart data for POST. It can also select an HTTP stream from the request's Accept or Content-Type headers. A framework must be able to return that stream when the selected transport needs one.

For WebSockets, the async view creates a context for the connection and passes messages to the GraphQL WebSocket handler. The client and server must share one of the enabled GraphQL WebSocket subprotocols. HTTP subscriptions use a separate stream response and do not use a WebSocket route.

References: strawberry/…/async_base_view.py• L316-451 strawberry/…/async_base_view.py• L565-629 strawberry/…/sync_base_view.py• L154-223 strawberry/…/streaming.py• L73-106

Framework bindings

The bindings differ mainly in how an endpoint is registered and how a response is produced. The shared view supplies the GraphQL rules. The framework layer supplies the route shape, request type, response type, and dependency or context mechanism.

FrameworkMain endpoint formWebSocket supportContext source
ASGIASGI application callableSame application handles a WebSocket scopeRequest and response objects
DjangoClass-based URL viewAsync Django view does not provide WebSocketsDjango request and response objects
FastAPIGraphQLRouter with HTTP and WebSocket routesRouter routeFastAPI dependencies
FlaskClass-based URL viewNo WebSocket support in the viewFlask request and response objects
AIOHTTPCallable added to an application routeSame view detects and prepares a WebSocketAIOHTTP request and response objects
ChannelsHTTP and WebSocket consumersDedicated GraphQL WebSocket consumerChannels consumer and scope
ChaliceChalice route handlerNot providedChalice request and temporal response
LitestarGenerated controller with route handlersController routeLitestar dependencies
QuartClass-based HTTP and WebSocket routesSame view detects WebSocket contextQuart request and response objects
SanicClass-based HTTP method viewNot provided by this viewSanic request and temporal response

ASGI application binding

The ASGI adapter is the direct async binding. It receives an ASGI scope and sends the completed response back through the ASGI callable. An HTTP scope uses Starlette request and response objects. A WebSocket scope uses the same shared execution path with a WebSocket message adapter.

This adapter is the base pattern for several async frameworks. FastAPI reuses its request and WebSocket behavior. Other frameworks keep the same shared view contract but map their own request and response APIs.

References: strawberry/…/__init__.py• L89-143 strawberry/…/__init__.py• L145-218

Django view binding

Django exposes GraphQL as a class-based URL view. The sync view returns an HttpResponse, while the async view is marked for Django's async dispatch path. Both views place a Django request and a response object in the default context so resolvers can read request state or change response headers and cookies.

The async binding can return a StreamingHttpResponse when shared transport selects an HTTP stream. It does not create a WebSocket endpoint. Applications that need GraphQL subscriptions use the Channels binding instead. The Django adapter also keeps Django's response and template rules for errors and the GraphQL IDE.

References: strawberry/…/views.py• L69-178 strawberry/…/views.py• L181-255

FastAPI router binding

FastAPI exposes GraphQL as a GraphQLRouter that can be included under an application prefix. The router creates HTTP routes for GET and POST and a WebSocket route for subscriptions. FastAPI dependencies provide the context and root value before shared GraphQL execution starts.

The default context keeps the request, response, and background task handle. A custom context can be a dictionary or a BaseContext object. This lets GraphQL resolvers use FastAPI dependency results without changing the shared transport path.

References: strawberry/…/router.py• L59-121 strawberry/…/router.py• L123-257 strawberry/…/router.py• L272-329

Flask view binding

Flask exposes GraphQL through a class-based view that is attached with Flask's URL rule system. The sync view uses Flask's request and response types. The async view keeps the same route shape but uses Flask's async dispatch support.

The Flask binding is HTTP-only. It creates a response before execution so resolver code can add headers or other response changes through the context. WebSocket subscriptions require a different integration or transport choice.

References: strawberry/…/views.py• L32-91 strawberry/…/views.py• L94-143

AIOHTTP view binding

AIOHTTP exposes GraphQL as a callable that applications add to a route. The view checks whether the request can be prepared as a WebSocket. It then either returns a normal AIOHTTP response or prepares a streaming response and writes each stream item before closing it.

The WebSocket adapter accepts JSON text from the connection and sends encoded messages through the AIOHTTP socket. The same request context carries the AIOHTTP request and the response under construction. This keeps response changes from resolvers available for both ordinary GraphQL replies and HTTP streams.

References: strawberry/…/views.py• L38-71 strawberry/…/views.py• L74-200

Channels consumer binding

Channels separates the HTTP and WebSocket sides into consumers. GraphQLProtocolTypeRouter maps the GraphQL path to the HTTP consumer for HTTP scopes and to the WebSocket consumer for WebSocket scopes. It can send other HTTP paths to the Django ASGI application.

The HTTP consumer adapts a Channels scope and request body to the shared request model. It returns either a normal response or a multipart HTTP stream. Its synchronous variant runs shared work through the Channels database-safe boundary while keeping the same HTTP contract.

The WebSocket consumer adapts its message queue to the shared WebSocket model. It starts the shared WebSocket run loop when the connection opens. It places incoming text messages and disconnect events in that queue. It sends encoded GraphQL messages or close signals through the consumer.

Channels also connects subscription code to channel-layer events. The consumer routes non-HTTP and non-WebSocket events to queues registered by each listener. A listener can join groups for the subscription lifetime and removes those memberships when the listener ends. Group membership uses a lock so concurrent listeners do not interleave joins and leaves for the same group. This gives a subscription a scoped way to receive cross-process events and stop receiving them during cleanup.

The WebSocket adapter accepts text messages that decode as JSON. A non-text message or invalid JSON becomes a transport error. During connection setup, the consumer chooses the first protocol offered by the client that the GraphQL view supports. It then accepts the connection with that protocol. GraphQLWebsocketCommunicator provides a test client that performs this protocol setup and turns subscription messages back into execution results.

References: strawberry/…/router.py• L26-89 strawberry/…/http_handler.py• L200-269 strawberry/…/http_handler.py• L271-418 strawberry/…/ws_handler.py• L27-60 strawberry/…/ws_handler.py• L68-205 strawberry/…/base.py• L51-164 strawberry/…/testing.py• L27-173

Chalice view binding

Chalice exposes GraphQL through an application route that calls GraphQLView.execute_request. The view uses Chalice's request object for input and a temporary response object while GraphQL runs. It then converts the result into Chalice's response shape.

This binding is sync and HTTP-only. It supports the shared request parsing and response customization hooks that fit a serverless HTTP request, but it does not provide WebSocket or HTTP streaming behavior.

References: strawberry/…/views.py• L18-81

Litestar controller binding

Litestar exposes GraphQL through a controller class created by make_graphql_controller. The generated controller registers GET, POST, and WebSocket handlers at the selected path. Litestar dependencies build the HTTP or WebSocket context before the shared view runs.

The context can be a dictionary or a BaseContext structure. The controller copies response headers, cookies, and background work into the final response. For a stream, it returns Litestar's stream response so the framework controls delivery.

References: strawberry/…/controller.py• L69-150 strawberry/…/controller.py• L159-193 strawberry/…/controller.py• L195-363 strawberry/…/controller.py• L383-443

Quart view binding

Quart exposes GraphQL through a class-based view that applications register for HTTP and WebSocket routes. The view uses the active Quart context to distinguish a normal request from a WebSocket request. It maps Quart's receive and send operations to the shared async WebSocket behavior.

The default context contains the request and response object. HTTP streams are returned as an async iterable with the headers selected by the shared transport. A deployment must register the WebSocket route separately from the HTTP route.

References: strawberry/…/views.py• L33-70 strawberry/…/views.py• L73-185

Sanic view binding

Sanic exposes GraphQL through an HTTP method view with separate GET and POST handlers. The view creates a temporary response for shared execution and turns the completed result into a Sanic HTTPResponse.

The Sanic view is HTTP-only for WebSocket handling. It does support async HTTP streams. For a stream it starts Sanic's response, writes each item, and completes the response before returning control to the framework.

References: strawberry/…/views.py• L29-127 strawberry/…/views.py• L129-170

Context and response handoff

The context is the bridge between a framework API and a resolver. Each adapter starts with a framework request and a response under construction. It places those objects in the default context or merges them with an application-supplied context.

The response under construction is important because resolver code can need to set headers, cookies, status data, or background work. After execution, the adapter copies those changes into the final response. The exact response features depend on the framework, but the shared expectation is that context changes affect the response returned by the route.

Applications should choose the context mechanism that matches the framework:

  • FastAPI and Litestar use dependency injection to build context values.
  • Django, Flask, AIOHTTP, Quart, Chalice, and Sanic provide overridable context hooks.
  • ASGI provides the request and response directly through its view hooks.
  • Channels provides the consumer and its connection scope. Channel-layer features are available only when the deployment configures a channel layer.

References: strawberry/…/__init__.py• L148-185 strawberry/…/router.py• L73-103 strawberry/…/views.py• L151-158 strawberry/…/http_handler.py• L307-319 strawberry/…/controller.py• L110-150

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the request adapter contract aligned with the shared view when a framework changes its request body, query, header, form, or WebSocket API.
  • Keep HTTP and WebSocket routes aligned with the enabled subscription protocols. A protocol enabled in the view must also be accepted by the framework route.
  • Preserve response headers from the shared stream transport when changing stream response creation. Clients and proxies use those headers to identify the stream.
  • Review sync bindings when adding a stream transport. Sync views must reject streaming requests instead of returning a normal GraphQL response.
  • Preserve the default request and response entries when merging custom FastAPI or Litestar context values. Resolvers may rely on them for framework actions.
  • For Channels changes, keep the WebSocket queue, protocol selection, connection task, and channel-layer group cleanup aligned with the subscription lifetime.

Important failure modes

TriggerConsequenceGuard
A client sends a method other than GET or POSTThe adapter returns HTTP 405 and does not execute the operationRoute only the supported methods or handle the method rejection at the framework boundary
A sync view receives an SSE or multipart subscription requestThe adapter returns HTTP 400 because it cannot produce a streaming responseUse an async binding for streaming subscriptions
A WebSocket route does not advertise a protocol enabled by the viewNo GraphQL WebSocket protocol is selected and the connection is rejectedConfigure the framework WebSocket route and client with a shared protocol
An AIOHTTP or Channels client sends a binary WebSocket messageThe adapter raises a non-text message error and the GraphQL message is not processedSend GraphQL WebSocket messages as text
A Channels client sends invalid JSONThe Channels adapter raises a non-JSON message error and the GraphQL message is not processedSend valid JSON messages for the selected GraphQL protocol
A multipart request arrives while uploads are disabledThe request is rejected as an unsupported content typeEnable multipart uploads only when the framework and deployment support the required upload handling
A FastAPI or Litestar context getter returns an unsupported valueContext creation raises InvalidCustomContext before schema executionReturn a supported dictionary or the framework's context base type
A Channels subscription listens without a channel layerSubscription setup raises a runtime error and cannot receive eventsConfigure a channel layer before using channel groups
An async Django resolver calls the synchronous ORM directlyDjango raises SynchronousOnlyOperationUse Django's async ORM methods or move the sync work behind an async boundary

Key files

FileWhy to read it
strawberry/…/async_base_view.pyDefines the shared async HTTP and WebSocket lifecycle used by ASGI-native adapters.
strawberry/…/sync_base_view.pyDefines the shared sync request and response lifecycle and its streaming limits.
strawberry/…/base.pyDefines common request checks, GraphQL IDE selection, and stream transport selection.
strawberry/…/streaming.pyDescribes the shared SSE and multipart stream contracts that framework responses must carry.
strawberry/…/__init__.pyShows the direct ASGI binding for HTTP scopes, WebSocket scopes, and response writing.
strawberry/…/router.pyShows how FastAPI routes and dependencies feed the shared async view.
strawberry/…/views.pyShows the sync and async Django view boundary.
strawberry/…/router.pyShows how Channels splits GraphQL HTTP and WebSocket routing.
strawberry/…/http_handler.pyShows how Channels adapts HTTP scopes and produces normal or multipart responses.
strawberry/…/ws_handler.pyShows how Channels queues WebSocket messages, selects a subprotocol, and connects the consumer to shared GraphQL WebSocket handling.
strawberry/…/base.pyShows how Channels channel-layer events reach a GraphQL subscription and how listener groups are serialized and cleaned up.
strawberry/…/testing.pyShows how GraphQL WebSocket protocol setup and subscription results are exercised through a Channels application.
strawberry/…/controller.pyShows controller creation, dependency-based context, and Litestar response forms.
strawberry/…/views.pyShows AIOHTTP WebSocket preparation and HTTP stream writing.
strawberry/…/client.pyShows the async test client path for JSON and multipart GraphQL requests through an AIOHTTP route.
strawberry/…/views.pyShows Flask sync and async class-based view binding.
strawberry/…/views.pyShows the Chalice serverless request and response boundary.
strawberry/…/views.pyShows Quart's shared HTTP and WebSocket view context.
strawberry/…/views.pyShows Sanic HTTP method routing and direct stream delivery.