Package: py-gql-client
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 runtimePython 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/CDGraphql is a query language developed by Facebook (https://graphql.org/)InstallationInstall it with:pipinstallpy-gql-clientUsageAfter installation you should compile code with runninggql-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 thegraphql_librarycreate the filequery.graphql:queryDogQuery($id:String!){dog(id:$id){idnamebreedage}}After compilation it will create the filequery.pyin the same folder:#!/usr/bin/env python3# @generated AUTOGENERATED file. Do not Change!fromdataclassesimportdataclass,fieldfromgql_client.runtime.variablesimportencode_variablesfromgqlimportgql,Clientfromgql.transport.exceptionsimportTransportQueryErrorfromfunctoolsimportpartialfromnumbersimportNumberfromtypingimportAny,AsyncGenerator,Dict,List,Generator,Optionalfromtimeimportperf_counterfromdataclasses_jsonimportDataClassJsonMixin,configfromgql_client.runtime.enum_utilsimportenum_field_metadatafrom.enum.dog_breedimportDogBreed# fmt: offQUERY:List[str]=["""query DogQuery($id: String!) {dog(id: $id) {idnamebreedage}}"""]classDogQuery:@dataclass(frozen=True)classDogQueryData(DataClassJsonMixin):@dataclass(frozen=True)classDog(DataClassJsonMixin):id:strname:Optional[str]breed:Optional[DogBreed]=field(metadata=enum_field_metadata(DogBreed))age:Optional[int]dog:Optional[Dog]# fmt: off@classmethoddefexecute(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)returnres.dog# fmt: off@classmethodasyncdefexecute_async(cls,client:Client,id:str)->Optional[DogQueryData.Dog]:variables:Dict[str,Any]={"id":id}new_variables=encode_variables(variables)response_text=awaitclient.execute_async(gql("".join(set(QUERY))),variable_values=new_variables)res=cls.DogQueryData.from_dict(response_text)returnres.dogFor 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:fromgqlimportClientfromgql.transport.aiohttpimportAIOHTTPTransportfromgql_client.runtime.graphql_clientimportGraphqlClientfromqueryimportDogQuerytransport=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 inexamplesdirectoryCustom ScalarsIf 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_pathoption.
In the configuration file you should havecustom_scalarsvariable of typeDict[str, CustomScalar]. Simple example:fromgql_client.compiler.renderer_dataclassesimportCustomScalarfromtypingimportDictcustom_scalars:Dict[str,CustomScalar]={"Cursor":CustomScalar(name="Cursor",type=str,),}CustomScalarhasencoder,decoderandmm_fieldwhen the custom scalar is defined with complex type that requires encoding\decoding from the string that is being sent in the graphql response.More featuresCreate fragments query files and share them between other query filesCompiler 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)LicensePy-gql-client isBSD Licenselicensed, as found in theLICENSEfile.