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 datetime import datetime
from gql_client.runtime.datetime_utils import DATETIME_FIELD_METADATA
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

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]
            age: Optional[int]
            breed: Optional[DogBreed] = field(metadata=enum_field_metadata(DogBreed))

        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

## 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.
