sgqlc Documentation

repository·master·Indexed 20 days ago

https://github.com/profusion/sgqlc

A simple GraphQL client for Python that enables developers to work with GraphQL schemas using native Python objects instead of raw query strings. It provides tools for type-safe query generation, automatic ISO 8601 date parsing, and mapping JSON results into Pythonic object hierarchies. Key components include sgqlc.types for schema declaration, sgqlc.operation for building queries, and sgqlc.endpoint for HTTP, WebSocket, and asynchronous (HTTPX) communication. It also includes the sgqlc-codegen tool for generating Python modules from GraphQL schemas.

Tokens
3.5K
Snippets
14
Records
22
Agent score
69%

What's inside sgqlc

  1. Overview of sgqlc modules

    master

    The sgqlc package is a simple GraphQL client for Python composed of three primary modules:

    • sgqlc.types: Used to declare GraphQL schemas in Python. This serves as the foundation for generating and interpreting queries. It includes submodules like:
      • sgqlc.types.datetime: Provides bindings for datetime and ISO 8601.
      • sgqlc.types.relay: Exposes Node, PageInfo, and Connection for Relay-style pagination.
    • sgqlc.operation: Uses the declared types to generate GraphQL queries and interpret the resulting JSON responses.
    • sgqlc.endpoint: Provides access to GraphQL endpoints. Specifically, sgqlc.endpoint.http provides the HTTPEndpoint class which uses urllib.request.urlopen() to communicate with servers.
  2. Use the sgqlc.operation module to build GraphQL queries

    master

    The sgqlc.operation module provides the core abstractions for constructing GraphQL operations (Queries, Mutations, etc.) and defining field selections. It allows you to build queries programmatically using a structured approach rather than manual string manipulation.

    Key components include:

    • Operation: Represents a top-level GraphQL operation (e.g., a Query or Mutation).
    • Selection: Represents a specific field or set of fields being selected.
    • Selector: Used to define how fields are selected within an operation.
    • SelectionList: A collection of selections used to build complex nested structures.
  3. Explore the sgqlc.types module

    master
    The sgqlc.types module provides the fundamental building blocks for defining GraphQL schemas and types within Python. It includes classes for representing core GraphQL types (like String, Int, Boolean, ID, Float), as well as structural components for building complex schemas such as Schema, Scalar, Enum, Union, Interface, Input, and Field. It also provides utilities for handling selection sets and arguments, such as Arg, ArgDict, Variable, and non_null wrappers.
  4. Use the sgqlc.endpoint module to interact with GraphQL APIs

    master

    The sgqlc.endpoint module provides the core abstractions for connecting to GraphQL endpoints. Depending on your transport requirements, you can use different sub-modules to handle the communication protocol:

    • sgqlc.endpoint.base: The base implementation for endpoints.
    • sgqlc.endpoint.http: For standard HTTP-based GraphQL communication.
    • sgqlc.endpoint.requests: An implementation using the popular requests library for HTTP transport.
    • sgqlc.endpoint.websocket: For real-time GraphQL communication via WebSockets.
  5. Use sgqlc.types sub-modules for specialized types

    master

    For specific GraphQL patterns and data types, use the specialized sub-modules:

    • sgqlc.types.datetime: For handling date and time related GraphQL scalars.
    • sgqlc.types.relay: For implementing the Relay specification (e.g., Connections, Edges, and Node interfaces).
  6. Use the sgqlc-codegen tool to generate Python modules from GraphQL schemas

    master
    The sgqlc-codegen tool is used to generate Python modules that represent a GraphQL schema. This allows you to interact with the GraphQL API using typed Python objects instead of writing raw GraphQL strings. The tool is part of the sgqlc.codegen module.
  7. Generate queries and interpret results using sgqlc.types and sgqlc.operation

    master

    Instead of writing raw strings, define your schema using sgqlc.types.Type (and subclasses like Connection or Field). Use sgqlc.operation.Operation to build queries by traversing the type tree. To map the JSON response back into native Python objects, use the overloaded addition operator: (operation + data).

    from sgqlc.endpoint.http import HTTPEndpoint
    from sgqlc.types import Type, Field, list_of
    from sgqlc.types.relay import Connection, connection_args
    from sgqlc.operation import Operation
    
    # 1. Declare types matching the schema
    class Issue(Type):
        number = int
        title = str
    
    class IssueConnection(Connection):
        nodes = list_of(Issue)
    
    class Repository(Type):
        issues = Field(IssueConnection, args=connection_args())
    
    class Query(Type):
        repository = Field(Repository, args={'owner': str, 'name': str})
    
    # 2. Build the operation
    op = Operation(Query)
    issues = op.repository(owner='profusion', name='sgqlc').issues(first=100)
    issues.nodes.number()
    issues.nodes.title()
    
    # 3. Execute and interpret
    endpoint = HTTPEndpoint('http://server.com/graphql')
    data = endpoint(op)
    repo = (op + data).repository
    for issue in repo.issues.nodes:
        print(issue.title)
  8. Generate operations from a GraphQL DSL (.gql) file

    master

    If you have existing GraphQL queries written in a DSL, you can use sgqlc-codegen operation to generate a Python module containing pre-built Operation objects.

    sgqlc-codegen operation \
        --schema github_schema.json \
        github_schema \
        sample_operations.py \
        sample_operations.gql
  9. Install and setup the sgqlc example environment

    master

    To run the basic examples, you need to install the project with all extras using poetry. You will also need a GitHub API token exported as GH_TOKEN to interact with the GitHub GraphQL API.

    Follow these steps:

    1. Install dependencies: poetry install --all-extras
    2. Activate the virtual environment (either via poetry shell or eval $(poetry env activate))
    3. Export your token: export GH_TOKEN=<your github API token>
    4. Navigate to the example directory and run the script.
    poetry install --all-extras
    
    # If using poetry-plugin-shell
    poetry shell
    # OR manually activate
    eval $(poetry env activate)
    
    export GH_TOKEN=<your github API token>
    
    cd examples/basic
    python3 01_http_endpoint.py $GH_TOKEN profusion/sgqlc
  10. Generate Python types from a GraphQL schema introspection

    master

    Use the sgqlc.introspection module to automate the creation of sgqlc.types classes. This is a two-step process: first, perform an introspection call to save the schema to JSON, then use sgqlc-codegen to generate the Python module.

    # 1. Introspect the schema and save to JSON
    python3 -m sgqlc.introspection \
        --exclude-deprecated \
        --exclude-description \
        -H "Authorization: bearer ${GH_TOKEN}" \
        https://api.github.com/graphql \
        github_schema.json
    
    # 2. Generate the Python module
    sgqlc-codegen schema github_schema.json github_schema.py
  11. Run the GitHub Agile Dashboard example

    master

    This example demonstrates a text-based Agile Dashboard for GitHub repositories, which works best for projects that utilize 'milestones'.

    To run the dashboard, you must first install dependencies, set your GitHub API token, and then execute the script to either save data or load it into a dashboard view.

    Prerequisites:

    • A GitHub API token exported to the GH_TOKEN environment variable.
    • Dependencies installed via poetry install --all-extras.
    # 1. Setup environment
    poetry install --all-extras
    poetry shell
    export GH_TOKEN=<your github API token>
    
    # 2. Navigate to example directory
    cd examples/github
    
    # 3. Save data to a local JSON file
    python3 github_agile_dashboard.py --token $GH_TOKEN profusion/sgqlc save data.json
    
    # 4. Launch the dashboard using the saved data
    python3 github_agile_dashboard.py --token $GH_TOKEN profusion/sgqlc dashboard --load data.json