Python GraphQL generated code client
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:
- 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_library
is where the folder where the graphql schema (or schemas) are locatedgraphql_library
is where you locate the queries that you'd like to compile (Query
,Mutation
andSubscription
are 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 (
--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.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file py-gql-client-1.0.1.tar.gz
.
File metadata
- Download URL: py-gql-client-1.0.1.tar.gz
- Upload date:
- Size: 14.4 kB
- Tags: Source
- Uploaded using 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
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 278b580bc78211216c62d436efb287aa6649aa7efb84c2e80050f11debd71b13 |
|
MD5 | de67e9353619ebab68875d51e2dcbe8a |
|
BLAKE2b-256 | 211b957e0c8b7cf42b1a18fdbc0d091ff5e15dcaae09aadd43b32bf5528a242b |
File details
Details for the file py_gql_client-1.0.1-py3-none-any.whl
.
File metadata
- Download URL: py_gql_client-1.0.1-py3-none-any.whl
- Upload date:
- Size: 18.1 kB
- Tags: Python 3
- Uploaded using 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
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | ecb816a285fc8d1df18e1c40a5b3335e11312feb5be9fe6ee2f4a14772f2473e |
|
MD5 | 2038a85f84c9ab2a0528bef0d51512f6 |
|
BLAKE2b-256 | da61505dcfcc0bb22599357cb6b787c991cba63272ffa446dd9662fb7a1c2f70 |