Metadata-Version: 2.1
Name: py-gql-client
Version: 0.0.8
Summary: Python GraphQL generated code client
Home-page: UNKNOWN
Author: Facebook Inc.
License: BSD License
Platform: UNKNOWN
Classifier: License :: OSI Approved :: BSD License
Classifier: Programming Language :: Python :: 3.7
Requires-Python: >=3.7
Description-Content-Type: text/markdown
Requires-Dist: graphql-core (>=3)
Requires-Dist: unicodecsv (>=0.14.1)
Requires-Dist: requests (>=2.22.0)
Requires-Dist: dataclasses-json (==0.3.2)

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 since it helps you guarantee the following:
1. GraphQL queries are valid - This is validated during compile time
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:

```bash
pip install py-gql-client
```

## Usage

After installation you should compile code with running
```bash
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`:

```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:


```python
#!/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:
```python
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.


