Skip to main content

Python schema-first GraphQL library based on GraphQL-core

Project description

python-gql

Python schema-first GraphQL library based on GraphQL-core.

Requirements

Python 3.7+

Installation

pip install python-gql

Getting start

import graphql
from gql import gql, make_schema, query, mutate

type_defs = gql("""
type Query {
    hello(name: String!): String!
}

type Post {
    author: String!
    comment: String!
}
type Mutation {
    addPost(author: String, comment: String): Post!
}
""")


@query
def hello(parent, info, name: str) -> str:
    return name


@mutate
def add_post(parent, info, author: str = None, comment: str = None) -> dict:
    return {'author': author, 'comment': comment}


schema = make_schema(type_defs)

q = """
query {
    hello(name: "graphql")
}
"""
result = graphql.graphql_sync(schema, q)
print(result.data)

# result: {'hello': 'graphql'}

q = """
mutation {
    addPost(author: "syfun", comment: "This is a good library.") {
        author
        comment
    }
}
"""
result = graphql.graphql_sync(schema, q)
print(result.data)

# result: {'addPost': {'author': 'syfun', 'comment': 'This is a good library.'}}

Build schema

This library is schema-first, so you must build a schema explicitly.

Here, we have two methods to build a schema, by a type definitions or a schema file.

from gql import gql, make_schema

type_defs = gql("""
type Query {
    hello(name: String!): String!
}
""")

schema = make_schema(type_defs)

gql function will check your type definitions syntax.

from gql import make_schema_from_file

schema = make_schema_from_file('./schema.graphql')

Resolver decorators

In Python, decorator is my favorite function, it save my life!

We can use query, mutation, subscribe to bind functions to GraphQL resolvers.

@query
def hello(parent, info, name: str) -> str:
    return name

These decorators will auto convert the snake function to camel one.

# add_port => addPost
@mutate
def add_post(parent, info, author: str = None, comment: str = None) -> dict:
    return {'author': author, 'comment': comment}

When the funcation name different from the resolver name, you can give a name argument to these decorators.

@query('hello')
def hello_function(parent, info, name: str) -> str:
    return name

About subscribe, please see gql-subscriptions.

Enum type decorator

Use enum_type decorator with a python Enum class.

from enum import Enum

from gql import enum_type


@enum_type
class Gender(Enum):
    MALE = 1
    FEMALE = 2

Custom Scalar

Use scalar_type decorator with a python class.

from gql import scalar_type


@scalar_type
class JSONString:
    description = "The `JSONString` represents a json string."

    @staticmethod
    def serialize(value: Any) -> str:
        return json.dumps(value)

    @staticmethod
    def parse_value(value: Any) -> dict:
        if not isinstance(value, str):
            raise TypeError(f'JSONString cannot represent non string value: {inspect(value)}')
        return json.loads(value)

    @staticmethod
    def parse_literal(ast, _variables=None):
        if isinstance(ast, StringValueNode):
            return json.loads(ast.value)

        return INVALID

Custom directive

from gql import gql, make_schema, query, SchemaDirectiveVisitor
from gql.resolver import default_field_resolver


type_defs = gql("""
directive @upper on FIELD_DEFINITION

type Query {
    hello(name: String!): String! @upper
}
""")

class UpperDirective(SchemaDirectiveVisitor):
    def visit_field_definition(self, field, object_type):
        original_resolver = field.resolve or default_field_resolver

        def resolve_upper(obj, info, **kwargs):
            result = original_resolver(obj, info, **kwargs)
            if result is None:
                return None
            return result.upper()

        field.resolve = resolve_upper
        return field

schema = make_schema(type_defs, directives={'upper': UpperDirective})

Apollo Federation

Example

Apollo Federation

Thanks to Ariadne

Framework support

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

python-gql-0.2.3.tar.gz (23.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

python_gql-0.2.3-py3-none-any.whl (24.6 kB view details)

Uploaded Python 3

File details

Details for the file python-gql-0.2.3.tar.gz.

File metadata

  • Download URL: python-gql-0.2.3.tar.gz
  • Upload date:
  • Size: 23.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.4 CPython/3.9.0 Darwin/20.2.0

File hashes

Hashes for python-gql-0.2.3.tar.gz
Algorithm Hash digest
SHA256 4822c67ac1da53e670c09d0ee21355fdfe4fba8dd80d5b7955041a3bcf5153e4
MD5 1bce0dcce7266e8c4114b93eacfe05c6
BLAKE2b-256 4976c1eadf186915731a7714ab62af94418e9ac5870e3e0bf39c84583e7d891e

See more details on using hashes here.

File details

Details for the file python_gql-0.2.3-py3-none-any.whl.

File metadata

  • Download URL: python_gql-0.2.3-py3-none-any.whl
  • Upload date:
  • Size: 24.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.4 CPython/3.9.0 Darwin/20.2.0

File hashes

Hashes for python_gql-0.2.3-py3-none-any.whl
Algorithm Hash digest
SHA256 cd8f6873efb473e6bc56c7f6e8a28e0d27b0189972c16e4f4842eec697dd9efd
MD5 087977d61866e431228e7c6490e0fb50
BLAKE2b-256 4047240ff38a3f77e0b9bf9e23ad0ba002cd3e3ce8ae5d1d5e832c619c52c5f3

See more details on using hashes here.

Supported by

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