Skip to main content

A python library that provides complexity calculation helpers for GraphQL

Project description

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 PyPI codecov

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:

pip install graphql-complexity

For Strawberry GraphQL integration, use the following command:

pip install graphql-complexity[strawberry-graphql]

Getting Started

Create a file named complexity.py with the following content:

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.

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.

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.

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. Use the following command to install the library with Strawberry support:

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.

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.

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

graphql_complexity-0.3.0.tar.gz (9.2 kB view details)

Uploaded Source

Built Distribution

graphql_complexity-0.3.0-py3-none-any.whl (11.5 kB view details)

Uploaded Python 3

File details

Details for the file graphql_complexity-0.3.0.tar.gz.

File metadata

  • Download URL: graphql_complexity-0.3.0.tar.gz
  • Upload date:
  • Size: 9.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.9.18

File hashes

Hashes for graphql_complexity-0.3.0.tar.gz
Algorithm Hash digest
SHA256 2467fb234bc9d7f7de770df696fcac8086a9f300f0cd522283c0fbefc2289d59
MD5 dc7a0f380b2d0351bf3280f0cc6d8e32
BLAKE2b-256 1601e68333c0f5216ffcd79b577db76c610a460c6997b567094040aef813db0c

See more details on using hashes here.

File details

Details for the file graphql_complexity-0.3.0-py3-none-any.whl.

File metadata

File hashes

Hashes for graphql_complexity-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 9cc0231654727119072a309f306c712e8d0ffc8a20b344de000e835f284e7c95
MD5 027555dee049955202cfbb32cd6edffa
BLAKE2b-256 e8b10a97cf55201f88c17de615fca2982f15b9b61f8ba11af7fdfa477f6d7d8b

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