{"id":13809941,"url":"https://github.com/profusion/sgqlc","last_synced_at":"2025-05-15T00:06:49.283Z","repository":{"id":37951669,"uuid":"117871564","full_name":"profusion/sgqlc","owner":"profusion","description":"Simple GraphQL Client","archived":false,"fork":false,"pushed_at":"2025-04-15T19:14:37.000Z","size":1689,"stargazers_count":529,"open_issues_count":39,"forks_count":87,"subscribers_count":12,"default_branch":"master","last_synced_at":"2025-05-06T01:02:39.412Z","etag":null,"topics":["graphql","graphql-client","python","python36"],"latest_commit_sha":null,"homepage":"https://sgqlc.readthedocs.io/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"isc","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/profusion.png","metadata":{"files":{"readme":"README.rst","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":"AUTHORS","dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-01-17T17:49:18.000Z","updated_at":"2025-04-23T17:05:59.000Z","dependencies_parsed_at":"2024-06-18T12:37:52.145Z","dependency_job_id":"a5407e3b-fa30-4880-ba21-3356891da3a3","html_url":"https://github.com/profusion/sgqlc","commit_stats":{"total_commits":243,"total_committers":34,"mean_commits":7.147058823529412,"dds":"0.19753086419753085","last_synced_commit":"d36984ac71165db6437c63b5aafd69b05eab52b9"},"previous_names":[],"tags_count":29,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/profusion%2Fsgqlc","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/profusion%2Fsgqlc/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/profusion%2Fsgqlc/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/profusion%2Fsgqlc/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/profusion","download_url":"https://codeload.github.com/profusion/sgqlc/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253601000,"owners_count":21934246,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["graphql","graphql-client","python","python36"],"created_at":"2024-08-04T02:00:40.302Z","updated_at":"2025-05-15T00:06:49.236Z","avatar_url":"https://github.com/profusion.png","language":"Python","readme":"`sgqlc` - Simple GraphQL Client\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. image:: https://github.com/profusion/sgqlc/actions/workflows/ci.yml/badge.svg\n    :target: https://github.com/profusion/sgqlc/actions/workflows/ci.yml\n\n.. image:: https://coveralls.io/repos/github/profusion/sgqlc/badge.svg?branch=master\n    :target: https://coveralls.io/github/profusion/sgqlc?branch=master\n\nIntroduction\n------------\n\nThis package offers an easy to use `GraphQL \u003chttp://graphql.org\u003e`_\nclient. It's composed of the following modules:\n\n- ``sgqlc.types``: declare GraphQL in Python, base to generate and\n  interpret queries. Submodule ``sgqlc.types.datetime`` will\n  provide bindings for ``datetime`` and ISO 8601, while\n  ``sgqlc.types.relay`` will expose ``Node``, ``PageInfo`` and\n  ``Connection``.\n\n- ``sgqlc.operation``: use declared types to generate and\n  interpret queries.\n\n- ``sgqlc.endpoint``: provide access to GraphQL endpoints, notably\n  ``sgqlc.endpoint.http`` provides ``HTTPEndpoint`` using\n  ``urllib.request.urlopen()``.\n\n\nWhat's GraphQL?\n===============\n\nStraight from http://graphql.org:\n\n   **A query language for your API**\n\n   GraphQL is a query language for APIs and a runtime for fulfilling\n   those queries with your existing data. GraphQL provides a complete\n   and understandable description of the data in your API, gives\n   clients the power to ask for exactly what they need and nothing\n   more, makes it easier to evolve APIs over time, and enables\n   powerful developer tools.\n\nIt was created by Facebook based on their problems and solutions using\n`REST \u003chttps://en.wikipedia.org/wiki/Representational_state_transfer\u003e`_\nto develop applications to consume their APIs. It was publicly\nannounced at\n`React.js Conf 2015 \u003chttps://reactjs.org/blog/2015/02/20/introducing-relay-and-graphql.html\u003e`_\nand started to gain traction since then. Right now there are big names\ntransitioning from REST to GraphQL:\n`Yelp \u003chttps://www.yelp.com/developers/graphql/guides/intro\u003e`_\n`Shopify \u003chttps://help.shopify.com/api/storefront-api/graphql\u003e`_\nand `GitHub \u003chttps://developer.github.com/v4/\u003e`_, that did an\nexcellent\n`post \u003chttps://githubengineering.com/the-github-graphql-api/\u003e`_\nto explain why they changed.\n\nA short list of advantages over REST:\n\n- Built-in schema, with documentation, strong typing and\n  introspection. There is no need to use\n  `Swagger \u003chttps://swagger.io\u003e`_ or any other external tools to play\n  with it. Actually GraphQL provides a standard in-browser IDE for\n  exploring GraphQL endpoints: https://github.com/graphql/graphiql;\n\n- Only the fields that you want. The queries must explicitly select which\n  fields are required, and that's all you're getting. If more fields\n  are added to the type, they **won't break** the API, since the new\n  fields won't be returned to old clients, as they didn't ask for such\n  fields. This makes much easier to keep APIs stable and **avoids\n  versioning**. Standard REST usually delivers all available fields in\n  the results, and when new fields are to be included, a new API\n  version is added (reflected in the URL path, or in an HTTP header);\n\n- All data in one request. Instead of navigating hypermedia-driven\n  RESTful services, like  discovering new ``\"_links\": {\"href\"...`` and\n  executing a new HTTP request, with GraphQL you specify nested\n  queries and let the whole navigation be done by the server. This\n  reduces latency **a lot**;\n\n- The resulting JSON object matches the given query exactly; if\n  you requested ``{ parent { child { info } } }``, you're going to\n  receive the JSON object ``{\"parent\": {\"child\": {\"info\": value }}}``.\n\nFrom GitHub's\n`Migrating from REST to GraphQL \u003chttps://developer.github.com/v4/guides/migrating-from-rest/\u003e`_\none can see these in real life::\n\n   $ curl -v https://api.github.com/orgs/github/members\n   [\n     {\n       \"login\": \"...\",\n       \"id\": 1234,\n       \"avatar_url\": \"https://avatars3.githubusercontent.com/u/...\",\n       \"gravatar_id\": \"\",\n       \"url\": \"https://api.github.com/users/...\",\n       \"html_url\": \"https://github.com/...\",\n       \"followers_url\": \"https://api.github.com/users/.../followers\",\n       \"following_url\": \"https://api.github.com/users/.../following{/other_user}\",\n       \"gists_url\": \"https://api.github.com/users/.../gists{/gist_id}\",\n       \"starred_url\": \"https://api.github.com/users/.../starred{/owner}{/repo}\",\n       \"subscriptions_url\": \"https://api.github.com/users/.../subscriptions\",\n       \"organizations_url\": \"https://api.github.com/users/.../orgs\",\n       \"repos_url\": \"https://api.github.com/users/.../repos\",\n       \"events_url\": \"https://api.github.com/users/.../events{/privacy}\",\n       \"received_events_url\": \"https://api.github.com/users/.../received_events\",\n       \"type\": \"User\",\n       \"site_admin\": true\n     },\n     ...\n   ]\n\nbrings the whole set of member information, however you just want name\nand avatar URL::\n\n   query {\n     organization(login:\"github\") { # select the organization\n       members(first: 100) {        # then select the organization's members\n         edges {  # edges + node: convention for paginated queries\n           node {\n             name\n             avatarUrl\n           }\n         }\n       }\n     }\n   }\n\nLikewise, instead of 4 HTTP requests::\n\n   curl -v https://api.github.com/repos/profusion/sgqlc/pulls/9\n   curl -v https://api.github.com/repos/profusion/sgqlc/pulls/9/commits\n   curl -v https://api.github.com/repos/profusion/sgqlc/issues/9/comments\n   curl -v https://api.github.com/repos/profusion/sgqlc/pulls/9/reviews\n\nA single GraphQL query brings all the needed information, and just the\nneeded information::\n\n   query {\n     repository(owner: \"profusion\", name: \"sgqlc\") {\n       pullRequest(number: 9) {\n         commits(first: 10) { # commits of profusion/sgqlc PR #9\n           edges {\n             node { commit { oid, message } }\n           }\n         }\n         comments(first: 10) { # comments of profusion/sgqlc PR #9\n           edges {\n             node {\n               body\n               author { login }\n             }\n           }\n         }\n         reviews(first: 10) { # reviews of profusion/sgqlc/ PR #9\n           edges { node { state } }\n         }\n       }\n     }\n   }\n\n\nMotivation to create `sgqlc`\n============================\n\nAs seen above, writing GraphQL queries is very easy, and it is equally easy to\ninterpret the results. So **what was the rationale to create sgqlc?**\n\n- GraphQL has its domain-specific language (DSL), and mixing two\n  languages is always painful, as seen with SQL + Python, HTML +\n  Python... Being able to write just Python in Python is much\n  better. Not to say that GraphQL naming convention is closer to\n  Java/JavaScript, using ``aNameFormat`` instead of Python's\n  ``a_name_format``.\n\n- Navigating dict-of-stuff is a bit painful:\n  ``d[\"repository\"][\"pullRequest\"][\"commits\"][\"edges\"][\"node\"]``,\n  since these are valid Python identifiers, we better write:\n  ``repository.pull_request.commits.edges.node``.\n\n- Handling new ``scalar`` types. GraphQL allows one to define new scalar\n  types, such as ``Date``, ``Time`` and ``DateTime``. Often these are\n  serialized as ISO 8601 strings and the user must parse them in their\n  application. We offer ``sgqlc.types.datetime`` to automatically\n  generate ``datetime.date``, ``datetime.time`` and\n  ``datetime.datetime``.\n\n- Make it easy to write dynamic queries, including nested. As seen,\n  GraphQL can be used to fetch lots of information in one go; however\n  if what you need (arguments and fields) changes based on some\n  variable, such as user input or cached data, then you need to\n  concatenate strings to compose the final query. This can be error\n  prone and servers may block you due to invalid queries. Some tools\n  \"solve\" this by parsing the query locally before sending it to\n  server. However usually the indentation is screwed and reviewing it\n  is painful. We change that approach: use\n  ``sgqlc.operation.Operation`` and it will always generate valid\n  queries, which can be printed out and properly indented. Bonus point\n  is that it can be used to later interpret the JSON results into native\n  Python objects.\n\n- Usability improvements whenever needed. For instance\n  `Relay \u003chttps://facebook.github.io/relay/\u003e`_ published their\n  `Cursor Connections Specification \u003chttps://facebook.github.io/relay/graphql/connections.htm\u003e`_\n  and its widely used. To load more data, you need to extend the\n  previous data with newly fetched information, updating not only the\n  nodes and edges, but also page information. This is done\n  automatically by ``sgqlc.types.relay.Connection``.\n\nIt also helps with code-generation, ``sgqlc-codegen`` can generate both\nthe classes matching a GraphQL Schema or functions to return\n``sgqlc.operation.Operation`` based on executable documents\nGraphQL Domain Specific Language (DSL).\n\n\nInstallation\n------------\n\nAutomatic::\n\n    pip install sgqlc\n\nFrom source using ``pip``::\n\n    pip install .\n\n\nUsage\n-----\n\nTo reach a GraphQL endpoint using synchronous `HTTPEndpoint` with a\nhand-written query (see more at ``examples/basic/01_http_endpoint.py``):\n\n.. code-block:: python\n\n   from sgqlc.endpoint.http import HTTPEndpoint\n\n   url = 'http://server.com/graphql'\n   headers = {'Authorization': 'bearer TOKEN'}\n\n   query = 'query { ... }'\n   variables = {'varName': 'value'}\n\n   endpoint = HTTPEndpoint(url, headers)\n   data = endpoint(query, variables)\n\n\nHowever, writing GraphQL queries and later interpreting the results\nmay be cumbersome. That's solved by our ``sgqlc.types``, which is\nusually paired with ``sgqlc.operation`` to generate queries and then\ninterpret results (see more at ``examples/basic/02_schema_types.py``). The\nexample below matches a subset of\n`GitHub API v4 \u003chttps://developer.github.com/v4/query/\u003e`_.\nIn GraphQL syntax it would be::\n\n   query {\n     repository(owner: \"profusion\", name: \"sgqlc\") {\n       issues(first: 100) {\n         nodes {\n           number\n           title\n         }\n         pageInfo {\n           hasNextPage\n           endCursor\n         }\n       }\n     }\n   }\n\nThe output JSON object is:\n\n.. code-block:: json\n\n   {\n     \"data\": {\n       \"repository\": {\n         \"issues\": {\n           \"nodes\": [\n             {\"number\": 1, \"title\": \"...\"},\n             {\"number\": 2, \"title\": \"...\"}\n           ]\n         },\n         \"pageInfo\": {\n            \"hasNextPage\": false,\n            \"endCursor\": \"...\"\n         }\n       }\n     }\n   }\n\n.. code-block:: python\n\n   from sgqlc.endpoint.http import HTTPEndpoint\n   from sgqlc.types import Type, Field, list_of\n   from sgqlc.types.relay import Connection, connection_args\n   from sgqlc.operation import Operation\n\n   # Declare types matching GitHub GraphQL schema:\n   class Issue(Type):\n       number = int\n       title = str\n\n   class IssueConnection(Connection):  # Connection provides page_info!\n       nodes = list_of(Issue)\n\n   class Repository(Type):\n       issues = Field(IssueConnection, args=connection_args())\n\n   class Query(Type):  # GraphQL's root\n       repository = Field(Repository, args={'owner': str, 'name': str})\n\n   # Generate an operation on Query, selecting fields:\n   op = Operation(Query)\n   # select a field, here with selection arguments, then another field:\n   issues = op.repository(owner=owner, name=name).issues(first=100)\n   # select sub-fields explicitly: { nodes { number title } }\n   issues.nodes.number()\n   issues.nodes.title()\n   # here uses __fields__() to select by name (*args)\n   issues.page_info.__fields__('has_next_page')\n   # here uses __fields__() to select by name (**kwargs)\n   issues.page_info.__fields__(end_cursor=True)\n\n   # you can print the resulting GraphQL\n   print(op)\n\n   # Call the endpoint:\n   data = endpoint(op)\n\n   # Interpret results into native objects\n   repo = (op + data).repository\n   for issue in repo.issues.nodes:\n       print(issue)\n\n\nWhy double-underscore and overloaded arithmetic methods?\n========================================================\n\nSince we don't want to clobber GraphQL fields, we cannot provide\nnicely named methods. Therefore we use overloaded methods such as\n``__iadd__``, ``__add__``, ``__bytes__`` (compressed GraphQL\nrepresentation) and ``__str__`` (indented GraphQL representation).\n\nTo select fields by name, use ``__fields__(*names, **names_and_args)``.\nThis helps with repetitive situations and can be used to \"include all\nfields\", or \"include all except...\":\n\n.. code-block:: python\n\n  # just 'a' and 'b'\n  type_selection.__fields__('a', 'b')\n  type_selection.__fields__(a=True, b=True) # equivalent\n\n  # a(arg1: value1), b(arg2: value2):\n  type_selection.__fields__(\n      a={'arg1': value1},\n      b={'arg2': value2})\n\n  # selects all possible fields\n  type_selection.__fields__()\n\n  # all but 'a' and 'b'\n  type_selection.__fields__(__exclude__=('a', 'b'))\n  type_selection.__fields__(a=False, b=False)\n\n\nCode Generator\n--------------\n\nManually converting an existing GraphQL schema to ``sgqlc.types``\nsubclasses is boring and error prone. To aid such task we offer a code\ngenerator that outputs a Python module straight from JSON of an\nintrospection call:\n\n.. code-block:: console\n\n   user@host$ python3 -m sgqlc.introspection \\\n        --exclude-deprecated \\\n        --exclude-description \\\n        -H \"Authorization: bearer ${GH_TOKEN}\" \\\n        https://api.github.com/graphql \\\n        github_schema.json\n   user@host$ sgqlc-codegen schema github_schema.json github_schema.py\n\nThis generates ``github_schema`` that provides the\n``sgqlc.types.Schema`` instance of the same name ``github_schema``.\nThen it's a matter of using that in your Python code, as in the example below\nfrom ``examples/github/github_agile_dashboard.py``:\n\n.. code-block:: python\n\n   from sgqlc.operation import Operation\n   from github_schema import github_schema as schema\n\n   op = Operation(schema.Query)  # note 'schema.'\n\n   # -- code below follows as the original usage example:\n\n   # select a field, here with selection arguments, then another field:\n   issues = op.repository(owner=owner, name=name).issues(first=100)\n   # select sub-fields explicitly: { nodes { number title } }\n   issues.nodes.number()\n   issues.nodes.title()\n   # here uses __fields__() to select by name (*args)\n   issues.page_info.__fields__('has_next_page')\n   # here uses __fields__() to select by name (**kwargs)\n   issues.page_info.__fields__(end_cursor=True)\n\n   # you can print the resulting GraphQL\n   print(op)\n\n   # Call the endpoint:\n   data = endpoint(op)\n\n   # Interpret results into native objects\n   repo = (op + data).repository\n   for issue in repo.issues.nodes:\n       print(issue)\n\n\nYou can also generate these operations given a GraphQL Domain Specific\nLanguage (DSL) operation:\n\n.. code-block::\n\n   # sample_operations.gql\n\n   query ListIssues($owner: String!, $name: String!) {\n       repository(owner: $owner, name: $name) {\n           issues(first: 100) {\n               nodes {\n                   number\n                   title\n               }\n               pageInfo {\n                   hasNextPage\n                   endCursor\n               }\n           }\n       }\n   }\n\n.. code-block:: console\n\n   user@host$ sgqlc-codegen operation \\\n      --schema github_schema.json \\\n      github_schema \\\n      sample_operations.py \\\n      sample_operations.gql\n\nThis generates ``sample_operations.py`` that provides the ``Operation``.\nThen it's a matter of using that in your Python code, as in the example below\nfrom ``examples/github/github-agile-dashboard.py``:\n\n.. code-block:: python\n\n   from sample_operations import Operations\n\n   op = Operations.query.list_issues\n\n   # you can print the resulting GraphQL\n   print(op)\n\n   # Call the endpoint:\n   data = endpoint(op, {'owner': owner, 'name': name})\n\n   # Interpret results into native objects\n   repo = (op + data).repository\n   for issue in repo.issues.nodes:\n       print(issue)\n\nAuthors\n-------\n\n- `Gustavo Sverzut Barbieri \u003cbarbieri@profusion.mobi\u003e`_\n\n\nLicense\n-------\n`sgqlc` is licensed under the `ISC \u003chttps://opensource.org/licenses/ISC\u003e`_.\n\n\nGetting started developing\n--------------------------\n\nYou need to use `poetry \u003chttps://python-poetry.org/docs/#installation\u003e`_.\n\n::\n\n    poetry install --all-extras --with dev\n    poetry shell\n\nInstall the `pre-commit \u003chttps://pre-commit.com/index.html#install\u003e`_:\n\n::\n\n   pre-commit install -f\n\nRun the tests (one of the below):\n\n::\n\n    pre-commit run -a            # run all tests: flake8, pytest, ...\n    pre-commit run -a flake8     # run only flake8\n    pre-commit run -a tests      # run only pytest (unit tests)\n\nKeep 100% coverage. You can look at the coverage report at\n``cover/index.html``.  To do that, prefer\n`doctest \u003chttps://docs.python.org/3.13/library/doctest.html\u003e`_\nso it serves as\nboth documentation and test. However we use\n`pytest \u003chttps://docs.pytest.org/\u003e`_ to write explicit tests that would be\nhard to express using ``doctest``.\n\nBuild and review the generated Sphinx documentation, and validate if your\nchanges look right:\n\n::\n\n    sphinx-build doc/source doc/build\n    open doc/build/html/index.html\n\n\nTo integrate changes from another branch, please **rebase** instead of\ncreating merge commits (\n`read more \u003chttps://git-scm.com/book/en/v2/Git-Branching-Rebasing\u003e`_).\n\nPublic Schemas\n--------------\n\nThe following repositories provides public schemas generated using ``sgqlc-codegen``:\n\n- `Mogost/sgqlc-schemas \u003chttps://github.com/Mogost/sgqlc-schemas\u003e`_ GitHub, Monday.com\n","funding_links":[],"categories":["JavaScript","Python","Implementations"],"sub_categories":["Python"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fprofusion%2Fsgqlc","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fprofusion%2Fsgqlc","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fprofusion%2Fsgqlc/lists"}