Skip to main content

GraphQL Modules for Ariadne

Project description

Ariadne

Build Status


Ariadne GraphQL Modules

Ariadne package for implementing Ariadne GraphQL schemas using modular approach.

For reasoning behind this work, please see this GitHub discussion.

See API reference file for documentation.

Installation

Ariadne GraphQL Modules can be installed using pip:

pip install ariadne-graphql-modules

Ariadne 0.15 or later is required for library to work.

Examples

Basic example

from datetime import date

from ariadne.asgi import GraphQL
from ariadne_graphql_modules import ObjectType, gql, make_executable_schema


class Query(ObjectType):
    __schema__ = gql(
        """
        type Query {
            message: String!
            year: Int!
        }
        """
    )

    @staticmethod
    def resolve_message(*_):
        return "Hello world!"

    @staticmethod
    def resolve_year(*_):
        return date.today().year


schema = make_executable_schema(Query)
app = GraphQL(schema=schema, debug=True)

Dependency injection

If __schema__ string contains other type, its definition should be provided via __requires__ attribute:

from typing import List, Optional

from ariadne.asgi import GraphQL
from ariadne_graphql_modules import ObjectType, gql, make_executable_schema

from my_app.users import User, get_user, get_last_users


class UserType(ObjectType):
    __schema__ = gql(
        """
        type User {
            id: ID!
            name: String!
            email: String
        }
        """
    )

    @staticmethod
    def resolve_email(user: User, info):
        if info.context["is_admin"]:
            return user.email

        return None


class UsersQueries(ObjectType):
    __schema__ = gql(
        """
        type Query {
            user(id: ID!): User
            users: [User!]!
        }
        """
    )
    __requires__ = [UserType]

    @staticmethod
    def resolve_user(*_, id: string) -> Optional[User]:
        return get_user(id=id)

    @staticmethod
    def resolve_users(*_, id: string) -> List[User]:
        return get_last_users()


# UsersQueries already knows about `UserType` so it can be omitted
# in make_executable_schema arguments
schema = make_executable_schema(UsersQueries)
app = GraphQL(schema=schema, debug=True)

Deferred dependencies

Optionally dependencies can be declared as deferred so they can be provided directly to make_executable_schema:

from typing import List, Optional

from ariadne.asgi import GraphQL
from ariadne_graphql_modules import DeferredType, ObjectType, gql, make_executable_schema

from my_app.users import User, get_user, get_last_users


class UserType(ObjectType):
    __schema__ = gql(
        """
        type User {
            id: ID!
            name: String!
            email: String
        }
        """
    )

    @staticmethod
    def resolve_email(user: User, info):
        if info.context["is_admin"]:
            return user.email

        return None


class UsersQueries(ObjectType):
    __schema__ = gql(
        """
        type Query {
            user(id: ID!): User
            users: [User!]!
        }
        """
    )
    __requires__ = [DeferredType("User")]

    @staticmethod
    def resolve_user(*_, id: string) -> Optional[User]:
        return get_user(id=id)

    @staticmethod
    def resolve_users(*_, id: string) -> List[User]:
        return get_last_users()


schema = make_executable_schema(UserType, UsersQueries)
app = GraphQL(schema=schema, debug=True)

Automatic case convertion between python_world and clientWorld

Resolving fields values

Use __aliases__ = convert_case to automatically set aliases for fields that convert case

from ariadne_graphql_modules import ObjectType, convert_case, gql


class UserType(ObjectType):
    __schema__ = gql(
        """
        type User {
            id: ID!
            fullName: String!
        }
        """
    )
    __aliases__ = convert_case

Converting fields arguments

Use __fields_args__ = convert_case on type to automatically convert field arguments to python case in resolver kwargs:

from ariadne_graphql_modules import MutationType, convert_case, gql

from my_app import create_user


class UserRegisterMutation(MutationType):
    __schema__ = gql(
        """
        type Mutation {
            registerUser(fullName: String!, email: String!): Boolean!
        }
        """
    )
    __fields_args__ = convert_case

    @staticmethod
    async def resolve_mutation(*_, full_name: str, email: str):
        user = await create_user(
            full_name=full_name,
            email=email,
        )
        return bool(user)

Converting inputs fields

Use __args__ = convert_case on type to automatically convert input fields to python case in resolver kwargs:

from ariadne_graphql_modules import InputType, MutationType, convert_case, gql

from my_app import create_user


class UserRegisterInput(InputType):
    __schema__ = gql(
        """
        input UserRegisterInput {
            fullName: String!
            email: String!
        }
        """
    )
    __args__ = convert_case


class UserRegisterMutation(MutationType):
    __schema__ = gql(
        """
        type Mutation {
            registerUser(input: UserRegisterInput!): Boolean!
        }
        """
    )
    __requires__ = [UserRegisterInput]

    @staticmethod
    async def resolve_mutation(*_, input: dict):
        user = await create_user(
            full_name=input["full_name"],
            email=input["email"],
        )
        return bool(user)

Roots merging

Query, Mutation and Subscription types are automatically merged into one by make_executable_schema:

from datetime import date

from ariadne.asgi import GraphQL
from ariadne_graphql_modules import ObjectType, gql, make_executable_schema


class YearQuery(ObjectType):
    __schema__ = gql(
        """
        type Query {
            year: Int!
        }
        """
    )

    @staticmethod
    def resolve_year(*_):
        return date.today().year


class MessageQuery(ObjectType):
    __schema__ = gql(
        """
        type Query {
            message: String!
        }
        """
    )

    @staticmethod
    def resolve_message(*_):
        return "Hello world!"


schema = make_executable_schema(YearQuery, MessageQuery)
app = GraphQL(schema=schema, debug=True)

Final schema will contain single Query type thats result of merged tupes:

type Query {
    message: String!
    year: Int!
}

Fields on final type will be ordered alphabetically.

Contributing

We are welcoming contributions to Ariadne GraphQL Modules! If you've found a bug or issue, feel free to use GitHub issues. If you have any questions or feedback, please let us know via GitHub discussions.

Also make sure you follow @AriadneGraphQL on Twitter for latest updates, news and random musings!

Crafted with ❤️ by Mirumee Software hello@mirumee.com

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

ariadne-graphql-modules-0.5.0.tar.gz (14.7 kB view details)

Uploaded Source

Built Distribution

ariadne_graphql_modules-0.5.0-py3-none-any.whl (22.2 kB view details)

Uploaded Python 3

File details

Details for the file ariadne-graphql-modules-0.5.0.tar.gz.

File metadata

File hashes

Hashes for ariadne-graphql-modules-0.5.0.tar.gz
Algorithm Hash digest
SHA256 7262ca0deab43f858a982c5316f7e6534548d7b29e6d79e41952d72af15320c8
MD5 099818f944c9d3f1974bce973aa8034f
BLAKE2b-256 ea57eee8e3c8619608c8c7df760469d8191d0f7432a3fa1d41b786e735f1470b

See more details on using hashes here.

File details

Details for the file ariadne_graphql_modules-0.5.0-py3-none-any.whl.

File metadata

File hashes

Hashes for ariadne_graphql_modules-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6f9dc158f73cd90fc7f06df4f5c5669d53f6709fa56bd9fed3a7781a599740ad
MD5 00107ffb37aa29de164c8a91d3af56d3
BLAKE2b-256 a895c283b8856347d9457724828021605fa8c0642333485ad9b02253152f78ee

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