AIOHTTPTransport¶
This transport uses the aiohttp library and allows you to send GraphQL queries using the HTTP protocol.
Reference: gql.transport.aiohttp.AIOHTTPTransport
This transport supports both standard GraphQL operations (queries, mutations) and subscriptions. Subscriptions are implemented using the multipart subscription protocol as implemented by Apollo GraphOS Router and other compatible servers.
This provides an HTTP-based alternative to WebSocket transports for receiving streaming subscription updates. It’s particularly useful when:
WebSocket connections are not available or blocked by infrastructure
You want to use standard HTTP with existing load balancers and proxies
The backend implements the multipart subscription protocol
Queries¶
import asyncio
from gql import Client, gql
from gql.transport.aiohttp import AIOHTTPTransport
async def main():
# Select your transport with a defined url endpoint
transport = AIOHTTPTransport(url="https://countries.trevorblades.com/graphql")
# Create a GraphQL client using the defined transport
client = Client(transport=transport)
# Provide a GraphQL query
query = gql(
"""
query getContinents {
continents {
code
name
}
}
"""
)
# Using `async with` on the client will start a connection on the transport
# and provide a `session` variable to execute queries on this connection
async with client as session:
# Execute the query
result = await session.execute(query)
print(result)
asyncio.run(main())
Subscriptions¶
The transport sends a standard HTTP POST request with an Accept header indicating
support for multipart responses:
Accept: multipart/mixed;subscriptionSpec="1.0", application/json
The server responds with a multipart/mixed content type and streams subscription
updates as separate parts in the response body. Each part contains a JSON payload
with GraphQL execution results.
import asyncio
import logging
from gql import Client, gql
from gql.transport.aiohttp import AIOHTTPTransport
logging.basicConfig(level=logging.INFO)
async def main():
transport = AIOHTTPTransport(url="https://gql-book-server.fly.dev/graphql")
# Using `async with` on the client will start a connection on the transport
# and provide a `session` variable to execute queries on this connection
async with Client(
transport=transport,
) as session:
# Request subscription
subscription = gql(
"""
subscription {
book {
title
author
}
}
"""
)
# Subscribe and receive streaming updates
async for result in session.subscribe(subscription):
print(f"Received: {result}")
asyncio.run(main())
How It Works¶
Message Format
Each message part follows this structure:
--graphql
Content-Type: application/json
{"payload": {"data": {...}, "errors": [...]}}
Heartbeats
Servers may send empty JSON objects ({}) as heartbeat messages to keep the
connection alive. These are automatically filtered out by the transport.
Error Handling
The protocol distinguishes between two types of errors:
GraphQL errors: Returned within the
payloadproperty alongside dataTransport errors: Returned with a top-level
errorsfield andnullpayload
End of Stream
The subscription ends when the server sends the final boundary marker:
--graphql--
Limitations¶
Subscriptions require the server to implement the multipart subscription protocol
Long-lived connections may be terminated by intermediate proxies or load balancers
Some server configurations may not support HTTP/1.1 chunked transfer encoding required for streaming
Authentication¶
There are multiple ways to authenticate depending on the server configuration.
Using HTTP Headers
transport = AIOHTTPTransport(
url='https://SERVER_URL:SERVER_PORT/graphql',
headers={'Authorization': 'token'}
)
Using HTTP Cookies
You can manually set the cookies which will be sent with each connection:
transport = AIOHTTPTransport(url=url, cookies={"cookie1": "val1"})
Or you can use a cookie jar to save cookies set from the backend and reuse them later.
In some cases, the server will set some connection cookies after a successful login mutation and you can save these cookies in a cookie jar to reuse them in a following connection (See issue 197):
jar = aiohttp.CookieJar()
transport = AIOHTTPTransport(url=url, client_session_args={'cookie_jar': jar})