Async Usage

If you use an async transport, you can use GQL asynchronously using asyncio.

  • put your code in an asyncio coroutine (method starting with async def)

  • use async with client as session: to connect to the backend and provide a session instance

  • use the await keyword to execute requests: await session.execute(...)

  • then run your coroutine in an asyncio event loop by running asyncio.run

Example:

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())

IPython

Warning

On some Python environments, like Jupyter or Spyder, which are using IPython, an asyncio event loop is already created for you by the environment.

In this case, running the above code might generate the following error:

RuntimeError: asyncio.run() cannot be called from a running event loop

If that happens, depending on the environment, you should replace asyncio.run(main()) by either:

await main()

OR:

loop = asyncio.get_running_loop()
loop.create_task(main())