Simple GraphQL Client

18 · active · verified Fri Apr 10

sgqlc is an easy-to-use Python library for interacting with GraphQL APIs. It provides modules for defining GraphQL types in Python, constructing and interpreting GraphQL queries and mutations as native Python objects, and connecting to GraphQL endpoints over HTTP. It also includes a command-line tool, `sgqlc-codegen`, to automatically generate Python type definitions from a GraphQL schema, promoting a schema-first approach. The library is actively maintained, with the current version being 18, released in February 2026.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a minimal GraphQL schema in Python, construct a query using `sgqlc.operation.Operation`, execute it against a public GraphQL endpoint, and interpret the results as native Python objects. It uses the `HTTPEndpoint` for synchronous requests. For more complex schemas, `sgqlc-codegen` can be used to generate Python types automatically.

import os
from sgqlc.endpoint.http import HTTPEndpoint
from sgqlc.operation import Operation
from sgqlc.types import Type, Field, list_of

# Define a simple GraphQL schema in Python
class Character(Type):
    name = Field(str)
    appears_in = Field(list_of(str))

class Query(Type):
    hero = Field(Character, args={'episode': str})
    characters = Field(list_of(Character))

class Schema(Type):
    query = Field(Query)

# Configure the GraphQL endpoint
# Replace with a real GraphQL API endpoint and token if available
url = os.environ.get('GRAPHQL_ENDPOINT', 'https://swapi-graphql.netlify.app/.netlify/functions/index')
headers = {}
# If your API requires authentication, uncomment and set an environment variable
# auth_token = os.environ.get('GRAPHQL_AUTH_TOKEN')
# if auth_token:
#    headers['Authorization'] = f'Bearer {auth_token}'

endpoint = HTTPEndpoint(url, headers)

# Build a query using the defined schema
op = Operation(Schema.query)

# Select the 'hero' field and its subfields
hero_query = op.hero(episode='JEDI')
hero_query.name()
hero_query.appears_in()

# Execute the query
print(f"Executing query to {url}:\n{op}\n")
data = endpoint(op)

# Interpret the results using the operation object
result = op + data

if result.errors:
    print("Errors:", result.errors)
else:
    hero = result.hero
    if hero:
        print(f"Hero: {hero.name}")
        print(f"Appears in: {', '.join(hero.appears_in)}")
    else:
        print("No hero found for episode JEDI.")

view raw JSON →