graphql-complexity


Namegraphql-complexity JSON
Version 0.3.2 PyPI version JSON
download
home_pagehttps://github.com/Checho3388/graphql-complexity
SummaryA python library that provides complexity calculation helpers for GraphQL
upload_time2024-03-14 18:36:51
maintainer
docs_urlNone
authorChecho3388
requires_python>=3.10,<4.0
licenseMIT
keywords graphql complexity query mutation subscription
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <img src="https://github.com/Checho3388/graphql-complexity/raw/main/.github/logo.png" width="150">

# GraphQL Complexity

Welcome to GraphQL-Complexity! This Python library provides functionality to compute the complexity of a GraphQL operation, contributing to better understanding and optimization of your GraphQL APIs. This library is designed to be stable, robust, and highly useful for developers working with GraphQL.

![Build](https://github.com/Checho3388/graphql-complexity/actions/workflows/python-build.yml/badge.svg)
[![PyPI](https://img.shields.io/pypi/v/graphql-complexity?label=pypi%20package)](https://pypi.org/project/graphql-complexity/)
[![codecov](https://codecov.io/gh/Checho3388/graphql-complexity/graph/badge.svg?token=4LH7AVN119)](https://codecov.io/gh/Checho3388/graphql-complexity)

## Features
- Compute complexity of GraphQL queries
- Multiple built-in estimators for complexity computation
- Customizable estimators for specific use cases
- Support for Strawberry GraphQL library


## Installation (Quick Start)

You can install the library via pip:

```shell
pip install graphql-complexity
```

For Strawberry GraphQL integration, use the following command:

```shell
pip install graphql-complexity[strawberry-graphql]
```

## Getting Started
Create a file named `complexity.py` with the following content:
```python
from graphql_complexity import get_complexity, SimpleEstimator
from graphql import build_schema


schema = build_schema("""
    type User {
        id: ID!
        name: String!
    }
    type Query {
        user: User
    }
""")

query = """
    query SomeQuery {
        user {
            id
            name
        }
    }
"""

complexity = get_complexity(
    query=query, 
    schema=schema,
    estimator=SimpleEstimator(complexity=10)
)
if complexity > 10:
    raise Exception("Query is too complex")
```

The library exposes the method `get_complexity` with the algorithm to compute the complexity of a GraphQL operation. 
The algorithm visits each node of the query and computes the complexity of each field using an **estimator**.


## Estimators

GraphQL-Complexity provides various built-in estimators for computing query complexity:

### SimpleEstimator
Estimate fields complexity based on constants for complexity and multiplier. This assigns a constant 
complexity value to each field and multiplies it by another constant, which is propagated along the depth of the query.

```python
from graphql_complexity import SimpleEstimator


estimator = SimpleEstimator(complexity=2)
```

### DirectivesEstimator

Define fields complexity using schema directives. This assigns a complexity value to each field and multiplies it 
by the depth of the query. It also supports the @complexity directive to assign a custom complexity value to a field.

```python
from graphql_complexity import DirectivesEstimator


schema = """
directive @complexity(
  value: Int!
) on FIELD_DEFINITION

type Query {
  oneField: String @complexity(value: 5)
  otherField: String @complexity(value: 1)
  withoutDirective: String
}
"""

estimator = DirectivesEstimator(schema)
```

### Custom estimator
Custom estimators can be defined to compute the complexity of a field using the `ComplexityEstimator` interface.

```python
from graphql_complexity import ComplexityEstimator


class CustomEstimator(ComplexityEstimator):
    def get_field_complexity(self, node, type_info, path) -> int:
        if node.name.value == "specificField":
            return 100
        return 1
```


## Supported libraries
This library is compatible with the following GraphQL libraries:

### Strawberry GraphQL

The library is compatible with [strawberry-graphql](https://pypi.org/project/strawberry-graphql/). 
Use the following command to install the library with Strawberry support:

```shell
poetry install --extras strawberry-graphql
```

To use the library with Strawberry GraphQL, use the `build_complexity_extension` method to build the complexity 
extension and add it to the schema. This method receives an estimator and returns a complexity extension that can be added to the schema.

```python
import strawberry
from graphql_complexity import SimpleEstimator
from graphql_complexity.extensions.strawberry_graphql import build_complexity_extension


@strawberry.type
class Query:
    @strawberry.field()
    def hello_world(self) -> str:
        return "Hello world!"

extension = build_complexity_extension(estimator=SimpleEstimator())
schema = strawberry.Schema(query=Query, extensions=[extension])

schema.execute_sync("query { helloWorld }")
```

The `build_complexity_extension` method accepts an estimator as optional argument giving the possibility to use one
of the built-in estimators or a custom estimator.

## Credits

Estimators idea was heavily inspired by [graphql-query-complexity](https://github.com/slicknode/graphql-query-complexity).


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/Checho3388/graphql-complexity",
    "name": "graphql-complexity",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.10,<4.0",
    "maintainer_email": "",
    "keywords": "graphql,complexity,query,mutation,subscription",
    "author": "Checho3388",
    "author_email": "ezequiel.grondona@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/47/f3/d19c26a9b02d223602f05569400479b49c367b324699e7a4837ade008a8d/graphql_complexity-0.3.2.tar.gz",
    "platform": null,
    "description": "<img src=\"https://github.com/Checho3388/graphql-complexity/raw/main/.github/logo.png\" width=\"150\">\n\n# GraphQL Complexity\n\nWelcome to GraphQL-Complexity! This Python library provides functionality to compute the complexity of a GraphQL operation, contributing to better understanding and optimization of your GraphQL APIs. This library is designed to be stable, robust, and highly useful for developers working with GraphQL.\n\n![Build](https://github.com/Checho3388/graphql-complexity/actions/workflows/python-build.yml/badge.svg)\n[![PyPI](https://img.shields.io/pypi/v/graphql-complexity?label=pypi%20package)](https://pypi.org/project/graphql-complexity/)\n[![codecov](https://codecov.io/gh/Checho3388/graphql-complexity/graph/badge.svg?token=4LH7AVN119)](https://codecov.io/gh/Checho3388/graphql-complexity)\n\n## Features\n- Compute complexity of GraphQL queries\n- Multiple built-in estimators for complexity computation\n- Customizable estimators for specific use cases\n- Support for Strawberry GraphQL library\n\n\n## Installation (Quick Start)\n\nYou can install the library via pip:\n\n```shell\npip install graphql-complexity\n```\n\nFor Strawberry GraphQL integration, use the following command:\n\n```shell\npip install graphql-complexity[strawberry-graphql]\n```\n\n## Getting Started\nCreate a file named `complexity.py` with the following content:\n```python\nfrom graphql_complexity import get_complexity, SimpleEstimator\nfrom graphql import build_schema\n\n\nschema = build_schema(\"\"\"\n    type User {\n        id: ID!\n        name: String!\n    }\n    type Query {\n        user: User\n    }\n\"\"\")\n\nquery = \"\"\"\n    query SomeQuery {\n        user {\n            id\n            name\n        }\n    }\n\"\"\"\n\ncomplexity = get_complexity(\n    query=query, \n    schema=schema,\n    estimator=SimpleEstimator(complexity=10)\n)\nif complexity > 10:\n    raise Exception(\"Query is too complex\")\n```\n\nThe library exposes the method `get_complexity` with the algorithm to compute the complexity of a GraphQL operation. \nThe algorithm visits each node of the query and computes the complexity of each field using an **estimator**.\n\n\n## Estimators\n\nGraphQL-Complexity provides various built-in estimators for computing query complexity:\n\n### SimpleEstimator\nEstimate fields complexity based on constants for complexity and multiplier. This assigns a constant \ncomplexity value to each field and multiplies it by another constant, which is propagated along the depth of the query.\n\n```python\nfrom graphql_complexity import SimpleEstimator\n\n\nestimator = SimpleEstimator(complexity=2)\n```\n\n### DirectivesEstimator\n\nDefine fields complexity using schema directives. This assigns a complexity value to each field and multiplies it \nby the depth of the query. It also supports the @complexity directive to assign a custom complexity value to a field.\n\n```python\nfrom graphql_complexity import DirectivesEstimator\n\n\nschema = \"\"\"\ndirective @complexity(\n  value: Int!\n) on FIELD_DEFINITION\n\ntype Query {\n  oneField: String @complexity(value: 5)\n  otherField: String @complexity(value: 1)\n  withoutDirective: String\n}\n\"\"\"\n\nestimator = DirectivesEstimator(schema)\n```\n\n### Custom estimator\nCustom estimators can be defined to compute the complexity of a field using the `ComplexityEstimator` interface.\n\n```python\nfrom graphql_complexity import ComplexityEstimator\n\n\nclass CustomEstimator(ComplexityEstimator):\n    def get_field_complexity(self, node, type_info, path) -> int:\n        if node.name.value == \"specificField\":\n            return 100\n        return 1\n```\n\n\n## Supported libraries\nThis library is compatible with the following GraphQL libraries:\n\n### Strawberry GraphQL\n\nThe library is compatible with [strawberry-graphql](https://pypi.org/project/strawberry-graphql/). \nUse the following command to install the library with Strawberry support:\n\n```shell\npoetry install --extras strawberry-graphql\n```\n\nTo use the library with Strawberry GraphQL, use the `build_complexity_extension` method to build the complexity \nextension and add it to the schema. This method receives an estimator and returns a complexity extension that can be added to the schema.\n\n```python\nimport strawberry\nfrom graphql_complexity import SimpleEstimator\nfrom graphql_complexity.extensions.strawberry_graphql import build_complexity_extension\n\n\n@strawberry.type\nclass Query:\n    @strawberry.field()\n    def hello_world(self) -> str:\n        return \"Hello world!\"\n\nextension = build_complexity_extension(estimator=SimpleEstimator())\nschema = strawberry.Schema(query=Query, extensions=[extension])\n\nschema.execute_sync(\"query { helloWorld }\")\n```\n\nThe `build_complexity_extension` method accepts an estimator as optional argument giving the possibility to use one\nof the built-in estimators or a custom estimator.\n\n## Credits\n\nEstimators idea was heavily inspired by [graphql-query-complexity](https://github.com/slicknode/graphql-query-complexity).\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A python library that provides complexity calculation helpers for GraphQL",
    "version": "0.3.2",
    "project_urls": {
        "Homepage": "https://github.com/Checho3388/graphql-complexity",
        "Repository": "https://github.com/Checho3388/graphql-complexity"
    },
    "split_keywords": [
        "graphql",
        "complexity",
        "query",
        "mutation",
        "subscription"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "93f43b638a3ba3a934ba8577b1ff4739cff9dbc2021d99a265e42cbbc0703603",
                "md5": "d5a2b565864564e502d3802fadc21fa3",
                "sha256": "c56fe40da1eace217ddb6d89b8a3218dcc7966e46cfac1050671073a34a276ef"
            },
            "downloads": -1,
            "filename": "graphql_complexity-0.3.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "d5a2b565864564e502d3802fadc21fa3",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10,<4.0",
            "size": 11591,
            "upload_time": "2024-03-14T18:36:50",
            "upload_time_iso_8601": "2024-03-14T18:36:50.162171Z",
            "url": "https://files.pythonhosted.org/packages/93/f4/3b638a3ba3a934ba8577b1ff4739cff9dbc2021d99a265e42cbbc0703603/graphql_complexity-0.3.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "47f3d19c26a9b02d223602f05569400479b49c367b324699e7a4837ade008a8d",
                "md5": "0d19297b4c201db889400e569ca15544",
                "sha256": "8b64b4b2a58c1735c155a399fbae6157419d2d2a72ea84c553b36b4d5a446f1f"
            },
            "downloads": -1,
            "filename": "graphql_complexity-0.3.2.tar.gz",
            "has_sig": false,
            "md5_digest": "0d19297b4c201db889400e569ca15544",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10,<4.0",
            "size": 9223,
            "upload_time": "2024-03-14T18:36:51",
            "upload_time_iso_8601": "2024-03-14T18:36:51.303595Z",
            "url": "https://files.pythonhosted.org/packages/47/f3/d19c26a9b02d223602f05569400479b49c367b324699e7a4837ade008a8d/graphql_complexity-0.3.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-03-14 18:36:51",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Checho3388",
    "github_project": "graphql-complexity",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "graphql-complexity"
}
        
Elapsed time: 0.23092s