AIOHTTPTransport

This transport uses the aiohttp library and allows you to send GraphQL queries using the HTTP protocol.

Reference: gql.transport.aiohttp.AIOHTTPTransport

Note

GraphQL subscriptions are not supported on the HTTP transport. For subscriptions you should use a websockets transport: WebsocketsTransport or AIOHTTPWebsocketsTransport.

import asyncio

from gql import Client, gql
from gql.transport.aiohttp import AIOHTTPTransport


async def main():

    transport = AIOHTTPTransport(url="https://countries.trevorblades.com/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,
        fetch_schema_from_transport=True,
    ) as session:

        # Execute single query
        query = gql(
            """
            query getContinents {
              continents {
                code
                name
              }
            }
        """
        )

        result = await session.execute(query)
        print(result)


asyncio.run(main())

Authentication

There are multiple ways to authenticate depending on the server configuration.

  1. Using HTTP Headers

transport = AIOHTTPTransport(
    url='https://SERVER_URL:SERVER_PORT/graphql',
    headers={'Authorization': 'token'}
)
  1. 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})