Skip to main content

Python GraphQL generated code client

Reason this release was yanked:

broken

Project description

Py-gql-client is a python library that creates strongly typed classes for querying graphql based on graphql schema. It is similar to other libraries that generates code for API schema types like gRPC and Thrift.

It is very helpful for building GraphQL based SDK in fast and safe way as it helps you guarantee the following:

  1. GraphQL queries are valid - Validated in compile time and runtime
  2. Python usage of queries is valid - User can validate it with using mypy (library is mypy compatible - http://mypy-lang.org/)
  3. Changes over time in graphql schema doesn't break existing SDKs - You can use verify flag of compiler and integrate it in your CI/CD

Graphql is a query language developed by Facebook (https://graphql.org/)

Installation

  • Install it with:
pip install py-gql-client

Usage

After installation you should compile code with running

gql-compiler {schema_library} {graphql_library}
  • schema_library is where the folder where the graphql schema (or schemas) are located
  • graphql_library is where you locate the queries that you'd like to compile (Query and Mutation are supported)

Example:

In the graphql_library create the file search.graphql:

query SearchQuery(
  $name: String!
  $after: Cursor
  $first: Int = 10
  $before: Cursor
  $last: Int
) {
  searchForNode(
    name: $name
    after: $after
    first: $first
    before: $before
    last: $last
  ) {
    edges {
      node {
        typename: __typename
        ... on Location {
          id
          externalId
          name
          locationType {
            name
          }
        }
      }
    }
  }
}

After compilation it will create the file search.py in the same folder:

#!/usr/bin/env python3
# @generated AUTOGENERATED file. Do not Change!

from dataclasses import dataclass
from datetime import datetime
from gql_client.runtime.datetime_utils import DATETIME_FIELD
from gql_client.runtime.graphql_client import GraphqlClient
from gql_client.runtime.client import OperationException
from gql_client.runtime.reporter import FailedOperationException
from functools import partial
from numbers import Number
from typing import Any, Callable, List, Mapping, Optional, Dict
from time import perf_counter
from dataclasses_json import DataClassJsonMixin


QUERY: List[str] = ["""
query SearchQuery(
  $name: String!
  $after: Cursor
  $first: Int = 10
  $before: Cursor
  $last: Int
) {
  searchForNode(
    name: $name
    after: $after
    first: $first
    before: $before
    last: $last
  ) {
    edges {
      node {
        typename: __typename
        ... on Location {
          id
          externalId
          name
          locationType {
            name
          }
        }
      }
    }
  }
}

"""]

@dataclass
class SearchQuery(DataClassJsonMixin):
    @dataclass
    class SearchQueryData(DataClassJsonMixin):
        @dataclass
        class SearchNodesConnection(DataClassJsonMixin):
            @dataclass
            class SearchNodeEdge(DataClassJsonMixin):
                @dataclass
                class Node(DataClassJsonMixin):
                    @dataclass
                    class LocationType(DataClassJsonMixin):
                        name: str

                    typename: str
                    id: str
                    externalId: Optional[str]
                    name: str
                    locationType: LocationType

                node: Optional[Node]

            edges: List[SearchNodeEdge]

        searchForNode: SearchNodesConnection

    data: SearchQueryData

    @classmethod
    # fmt: off
    def execute(cls, client: GraphqlClient, name: str, after: Optional[str] = None, first: Optional[int] = 10, before: Optional[str] = None, last: Optional[int] = None) -> SearchQueryData.SearchNodesConnection:
        # fmt: off
        variables: Dict[str, Any] = {"name": name, "after": after, "first": first, "before": before, "last": last}
        try:
            network_start = perf_counter()
            response_text = client.call(''.join(set(QUERY)), variables=variables)
            decode_start = perf_counter()
            res = cls.from_json(response_text).data
            decode_time = perf_counter() - decode_start
            network_time = decode_start - network_start
            client.reporter.log_successful_operation("SearchQuery", variables, network_time, decode_time)
            return res.searchForNode
        except OperationException as e:
            raise FailedOperationException(
                client.reporter,
                e.err_msg,
                "SearchQuery",
                variables,
            )

For using the new class run the following:

from requests import Session
from gql_client.runtime.graphql_client import GraphqlClient
client = GraphqlClient("http://.../graph/query", Session())
result = SearchQuery.execute(client, ...)
...

More features

  • Create fragments query files and share them between other query files
  • Compiler has an option to only verify compiled query files without re-genrating them
  • Compiler can be configured to raise an error if queries use deprecated fields

License

Py-gql-client is BSD License licensed, as found in the LICENSE file.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

py-gql-client-0.0.11.tar.gz (15.9 kB view hashes)

Uploaded Source

Built Distribution

py_gql_client-0.0.11-py3-none-any.whl (19.4 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page