py-gql-client 1.0.1
Python GraphQL generated code client
License: BSD License
Requires Python: >=3.6

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:

```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`, `Mutation` and `Subscription` are supported)

Example:

In the `graphql_library` create the file `query.graphql`:

```graphql
query DogQuery($id: String!) {
    dog(id: $id) {
        id
        name
        breed
        age
    }
}
```

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


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

from dataclasses import dataclass, field
from gql_client.runtime.variables import encode_variables
from gql import gql, Client
from gql.transport.exceptions import TransportQueryError
from functools import partial
from numbers import Number
from typing import Any, AsyncGenerator, Dict, List, Generator, Optional
from time import perf_counter
from dataclasses_json import DataClassJsonMixin, config

from gql_client.runtime.enum_utils import enum_field_metadata
from .enum.dog_breed import DogBreed


# fmt: off
QUERY: List[str] = ["""
query DogQuery($id: String!) {
    dog(id: $id) {
        id
        name
        breed
        age
    }
}
"""
]


class DogQuery:
    @dataclass(frozen=True)
    class DogQueryData(DataClassJsonMixin):
        @dataclass(frozen=True)
        class Dog(DataClassJsonMixin):
            id: str
            name: Optional[str]
            breed: Optional[DogBreed] = field(metadata=enum_field_metadata(DogBreed))
            age: Optional[int]

        dog: Optional[Dog]

    # fmt: off
    @classmethod
    def execute(cls, client: Client, id: str) -> Optional[DogQueryData.Dog]:
        variables: Dict[str, Any] = {"id": id}
        new_variables = encode_variables(variables)
        response_text = client.execute(
            gql("".join(set(QUERY))), variable_values=new_variables
        )
        res = cls.DogQueryData.from_dict(response_text)
        return res.dog

    # fmt: off
    @classmethod
    async def execute_async(cls, client: Client, id: str) -> Optional[DogQueryData.Dog]:
        variables: Dict[str, Any] = {"id": id}
        new_variables = encode_variables(variables)
        response_text = await client.execute_async(
            gql("".join(set(QUERY))), variable_values=new_variables
        )
        res = cls.DogQueryData.from_dict(response_text)
        return res.dog
```

For using the new class you first need to initialize a graphql client with gql library (https://github.com/graphql-python/gql). There are many options in the library for defining the underlying transport so check the documentation to learn more.

Full simple example is the following:
```python
from gql import Client
from gql.transport.aiohttp import AIOHTTPTransport
from gql_client.runtime.graphql_client import GraphqlClient
from query import DogQuery

transport = AIOHTTPTransport(url="http://.../graph/query")
client = Client(transport=transport, fetch_schema_from_transport=True)
result = DogQuery.execute(client, id="1000")
...
```

You can find many more examples in `examples` directory

## Custom Scalars

If your graphql schema contains custom scalars you should create python configuration file with the definitions of the custom scalars and use in the compilation command with `--config_path` option.
In the configuration file you should have `custom_scalars` variable of type `Dict[str, CustomScalar]`. Simple example:
```python
from gql_client.compiler.renderer_dataclasses import CustomScalar
from typing import Dict

custom_scalars: Dict[str, CustomScalar] = {
    "Cursor": CustomScalar(
        name="Cursor",
        type=str,
    ),
}
```
`CustomScalar` has `encoder`, `decoder` and `mm_field` when the custom scalar is defined with complex type that requires encoding\decoding from the string that is being sent in the graphql response.

## 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 (`--verify` option)
* Compiler can be configured to raise an error if queries use deprecated fields (`--allow-deprecated` option)

## License

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