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:
- GraphQL queries are valid - Validated in compile time and runtime
- Python usage of queries is valid - User can validate it with using mypy (library is mypy compatible - http://mypy-lang.org/)
- 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_libraryis where the folder where the graphql schema (or schemas) are locatedgraphql_libraryis where you locate the queries that you'd like to compile (Query,MutationandSubscriptionare supported)
Example:
In the graphql_library create the file query.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:
#!/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:
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:
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 (
--verifyoption) - Compiler can be configured to raise an error if queries use deprecated fields (
--allow-deprecatedoption)
License
Py-gql-client is BSD License licensed, as found in the LICENSE file.
Metadata
Release files for py-gql-client 1.0.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| py-gql-client-1.0.1.tar.gz | 14.4 kB | Without provenance | Details for py-gql-client-1.0.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| py_gql_client-1.0.1-py3-none-any.whl | Python 3 | none | any | Details for py_gql_client-1.0.1-py3-none-any.whl |
Total release size: 32.6 kB
Release files / py-gql-client-1.0.1.tar.gz
| Download URL | py-gql-client-1.0.1.tar.gz |
|---|---|
| Size | 14.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
278b580bc78211216c62d436efb287aa6649aa7efb84c2e80050f11debd71b13
|
|
BLAKE2b-256 checksum How to use checksums |
211b957e0c8b7cf42b1a18fdbc0d091ff5e15dcaae09aadd43b32bf5528a242b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/3.3.0 pkginfo/1.6.1 requests/2.25.1 setuptools/51.0.0 requests-toolbelt/0.9.1 tqdm/4.55.1 CPython/3.6.12
|
Release files / py_gql_client-1.0.1-py3-none-any.whl
| Download URL | py_gql_client-1.0.1-py3-none-any.whl |
|---|---|
| Size | 18.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
ecb816a285fc8d1df18e1c40a5b3335e11312feb5be9fe6ee2f4a14772f2473e
|
|
BLAKE2b-256 checksum How to use checksums |
da61505dcfcc0bb22599357cb6b787c991cba63272ffa446dd9662fb7a1c2f70
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/3.3.0 pkginfo/1.6.1 requests/2.25.1 setuptools/51.0.0 requests-toolbelt/0.9.1 tqdm/4.55.1 CPython/3.6.12
|
Security for py-gql-client 1.0.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.