gql: GraphQL Client for Python
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
- breaking As of v4.0.0, the `gql()` and `dsl_gql()` functions now return a `GraphQLRequest` object instead of a `DocumentNode`. All `client.execute()` and `client.subscribe()` methods also now accept a `GraphQLRequest` object as their primary argument.
- breaking The `AIOHTTPTransport`'s `ssl` parameter now defaults to `True` (enabling SSL certificate verification) starting from v4.0.0 (introduced in v4.0.0a0). Previously, it defaulted to `False` which could lead to security vulnerabilities by accepting self-signed certificates without warning.
- breaking The `ConnectionClosed` exception has been replaced by `TransportConnectionClosed` for connection-related errors.
- gotcha When using synchronous `client.execute()` or `client.subscribe()` methods from an asynchronous transport (like `AIOHTTPTransport`) in environments where an asyncio event loop is already running (e.g., Jupyter notebooks, IPython), it might cause issues or block. `gql` will try to run an event loop itself, which conflicts with an already running one.
Install
-
pip install "gql[all]" -
pip install gql
Imports
- Client
from gql import Client
- gql
from gql import gql
- AIOHTTPTransport
from gql.transport.aiohttp import AIOHTTPTransport
- WSAsyncTransport
from gql.transport.websockets import WSAsyncTransport
- GraphQLRequest
from gql.graphql_request import GraphQLRequest
- dsl_gql
from gql.dsl import dsl_gql
- DSLQuery
from gql.dsl import DSLQuery
- DSLSchema
from gql.dsl import DSLSchema
Quickstart
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())