gql: GraphQL Client for Python

4.0.0 · active · verified Sun Mar 29

gql is a powerful and flexible GraphQL client library for Python, designed to simplify interacting with GraphQL APIs. It supports both synchronous and asynchronous operations, offering various transports like HTTP (via aiohttp, httpx, requests) and WebSockets. The library plays well with `graphql-core` and other GraphQL implementations, enabling features like local schema validation and dynamic query composition using a DSL module. The current stable version is 4.0.0, with active development including beta releases (e.g., v4.3.0b0) leading to future minor or major updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up an asynchronous `gql` client using `AIOHTTPTransport`, define a GraphQL query, and execute it. It includes handling potential authentication headers and uses the recommended `async with client as session:` pattern for managing connections. Ensure you have `aiohttp` installed (e.g., `pip install "gql[aiohttp]"` or `pip install "gql[all]"`) for this example to run.

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

async def main():
    # Replace with your GraphQL endpoint
    # For a real application, consider using environment variables for the URL and auth.
    graphql_url = os.environ.get('GRAPHQL_ENDPOINT_URL', 'https://countries.trevorblades.com/graphql')
    auth_token = os.environ.get('GRAPHQL_AUTH_TOKEN', '')

    headers = {}
    if auth_token:
        headers['Authorization'] = f'Bearer {auth_token}'

    # Select your transport
    transport = AIOHTTPTransport(url=graphql_url, headers=headers)

    # Create a GraphQL client
    client = Client(transport=transport, fetch_schema_from_transport=True)

    # Provide a GraphQL query (now returns GraphQLRequest object in v4+)
    query = gql(
        """
        query getContinents {
            continents {
                code
                name
            }
        }
        """
    )

    # Using `async with` on the client will start a connection
    # and provide a `session` variable to execute queries on this connection.
    async with client as session:
        # Execute the query (now accepts GraphQLRequest object in v4+)
        result = await session.execute(query)
        print(result)

if __name__ == "__main__":
    # If an asyncio event loop is already running, use this instead:
    # import nest_asyncio
    # nest_asyncio.apply()
    # asyncio.run(main())
    asyncio.run(main())

view raw JSON →