Skip to main content

A Python library for making GraphQL requests easier!

Project description

gqlrequests - Create requests to GraphQL APIs with no strings attached 😉

Pytests and Coverage Code Quality codecov

Define GraphQL types in Python as classes, then use them to automatically build queries. Or even simpler; gqlrequests will automatically build the classes for you given the api endpoint by using introspection! (Now that's awesome). You no longer need to define your requests as multiline strings (hence no strings attached).

These examples show what I envision this module to become. Examples of how it will work:

import gqlrequests

class Episode(gqlrequests.QueryBuilder):
    name: str
    length: float

class Character(gqlrequests.QueryBuilder):
    name: str
    appearsIn: list[Episode]

print(Character)
# type Character {
#     name: String
#     appearsIn: [Episode]
# }
#

print(Character().build())
# {
#     name
#     appearsIn {
#         name
#         length
#     }
# }

print(Character(fields=["name"]).build())
# {
#     name
# }

print(Character(indents=2).build()) # Default indent is 4
# {
#   name
#   appearsIn {
#     name
#     length
#   }
# }


getCharacter = Character()  # Function name is variable name by default
print(getCharacter(name="Luke").build())
# getCharacter(name: "Luke") {
#     name
#     appearsIn {
#         name
#         length
#     }
# }

episode_func = Episode(func_name="appearsIn")

characters_query = Character()
characters_query.appearsIn = episode_func(minLength=5)

print(characters_query.build())
# {
#     name
#     appearsIn(minLength: 5) {
#         name
#         length
#     }
# }

Interacting with a GraphQL endpoint (gql already does this, but this would be nicer imo):

import gqlrequests
import asyncio

# Normal query
gqlclient = gqlrequests.Client(
    api_endpoint="api.example.com/gql",
    authorization="abcdefghijklmnopqrstuvwxyz"
)

schema, types = gqlclient.introspect()
character_search_query = types.Character(func_name="findCharacter")

character = gqlclient.execute(character_search_query(name="Luke").build())
print(character.name)

# Asynchronous queries
RootQuery = schema.RootQuery
async def main():
    gqlclient = gqlrequests.AsyncClient(
        api_endpoint="api.example.com/gql",
        authorization="abcdefghijklmnopqrstuvwxyz"
    )

    queries = asyncio.gather(
        gqlclient.execute(RootQuery(fields=["character"]).build()),
        gqlclient.execute(RootQuery(fields=["episode"]).build())
    )

    character, episode = await queries

    # Or simply:
    character = await gqlclient.execute(RootQuery().build())

asyncio.run(main())
"""Subscribing to a graphql websocket"""
import gqlrequests
import asyncio

schema, types = gqlrequests.introspect()
RootMutation = schema.RootMutation


# Example of how the type of RootMutation.live could look like:
#
# class LiveViewers(gqlrequests.QueryBuilder):
#     viewers: int
#     measurementTimeUnix: int


async def main():
    gqlclient = gqlrequests.Client(
        api_endpoint="api.example.com/gql",
        authorization="abcdefghijklmnopqrstuvwxyz"
    )

    query_string = RootMutation(fields=["live"]).build()

    async with gqlclient.subscribe(query_string) as subscription:
        async for data in subscription:
            assert isinstance(data, LiveViewers)

            print(data.viewers, data.measurementTimeUnix)
            if data.viewers < 10: break

asyncio.run(main())

Edge cases

Some attributes are reserved keywords in Python, such as from, is and not. These cannot be referenced to by property like this: some_query_result.from. This can be circumvented by adding leading or trailing underscores, then passing the strip_underscores argument to the build method.

class Time(gqlrequests.QueryBuilder):
    _from: int
    _to: int
    value: float

print(Time().build(strip_underscores=True))
# {
#     from
#     to
#     value
# }

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

gqlrequests-0.0.9.tar.gz (8.2 kB view details)

Uploaded Source

Built Distribution

gqlrequests-0.0.9-py3-none-any.whl (7.1 kB view details)

Uploaded Python 3

File details

Details for the file gqlrequests-0.0.9.tar.gz.

File metadata

  • Download URL: gqlrequests-0.0.9.tar.gz
  • Upload date:
  • Size: 8.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.9.19

File hashes

Hashes for gqlrequests-0.0.9.tar.gz
Algorithm Hash digest
SHA256 22e8d275ce439af8bb2e9960cc86e13f5e67705caded194fa24f82b6eabd3974
MD5 9850cf575d5cf71ee231890e77db1fa6
BLAKE2b-256 97c20ac4eecadb4d7473be41a4f3c1ebca8686fdd062c97f4de46c257a6c8232

See more details on using hashes here.

File details

Details for the file gqlrequests-0.0.9-py3-none-any.whl.

File metadata

  • Download URL: gqlrequests-0.0.9-py3-none-any.whl
  • Upload date:
  • Size: 7.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.9.19

File hashes

Hashes for gqlrequests-0.0.9-py3-none-any.whl
Algorithm Hash digest
SHA256 3fa5e4b329e2733636a47319f0ec09c8b6d7cd95187b7a18b978281450dcb42c
MD5 af1c9e0bd57dedd54207e53148e12ebc
BLAKE2b-256 58f31169a708f99c3480cf2083819883e32aab7a2420affc1acb92ac585db34e

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page