Python GraphQL Client
A Python client for interacting with GraphQL APIs, offering synchronous, asynchronous, and websocket-based subscription capabilities. It provides simple interfaces for sending queries, mutations, and subscribing to real-time data streams. The current version is 0.4.5, with a relatively active release cadence addressing features and maintenance.
Warnings
- gotcha The library provides distinct client classes for synchronous (`GraphQLClient`), asynchronous (`GraphQLClientAIOHTTP`), and websocket subscriptions (`GraphQLClientWebsockets`). Ensure you use the correct client for your desired operation, as they leverage different underlying HTTP/websocket libraries.
- gotcha GraphQL API errors (i.e., errors returned in the `errors` field of the GraphQL response body) are not automatically raised as Python exceptions by the client. You must manually inspect the `data` and `errors` fields in the returned dictionary to handle successful data or API-level errors.
- gotcha When passing custom HTTP headers (e.g., for authentication), ensure they are provided as a dictionary to the `headers` parameter during client initialization or when calling the `execute` method. For subscriptions, initial payload headers can also be set via the `init_payload` parameter in `GraphQLClientWebsockets`.
Install
-
pip install python-graphql-client
Imports
- GraphQLClient
from graphql_client import GraphQLClient
- GraphQLClientAIOHTTP
from graphql_client import GraphQLClientAIOHTTP
- GraphQLClientWebsockets
from graphql_client import GraphQLClientWebsockets
Quickstart
import os
import json
from graphql_client import GraphQLClient
# Using a public GraphQL API endpoint for demonstration
endpoint = os.environ.get("GRAPHQL_ENDPOINT", "https://countries.trevorblades.com/graphql")
# Initialize the synchronous client
client = GraphQLClient(endpoint=endpoint)
# Define your GraphQL query
query = """
query GetCountryDetails($code: ID!) {
country(code: $code) {
name
capital
currency
}
}
"""
# Define variables for the query
variables = {"code": "BR"}
# Execute the query
response_data = client.execute(query=query, variables=variables)
# Print the raw JSON response
print("Raw Response:", json.dumps(response_data, indent=2))
# Accessing data and errors
if 'data' in response_data and response_data['data']:
country = response_data['data']['country']
if country:
print(f"\nCountry: {country['name']}")
print(f"Capital: {country['capital']}")
print(f"Currency: {country['currency']}")
else:
print("\nError fetching country details.")
if 'errors' in response_data:
print("GraphQL Errors:", json.dumps(response_data['errors'], indent=2))