Python GraphQL Client

0.4.5 · active · verified Tue Apr 14

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a synchronous `GraphQLClient`, define a query with variables, execute it, and process the returned JSON data and potential errors. Remember to replace the `GRAPHQL_ENDPOINT` with your actual GraphQL API endpoint.

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

view raw JSON →