Skip to content

Checho3388/graphql-complexity

Repository files navigation

GraphQL Complexity Logo

GraphQL Complexity

Build PyPI codecov Downloads Python Version License: MIT

Python library to compute the complexity of a GraphQL operation. Protect your API from expensive queries and potential DoS attacks by calculating complexity before execution.

🎮 Try it live: graphql-complexity playground 📖 Full docs: graphql-complexity.readthedocs.io


Installation

pip install graphql-complexity

# With Strawberry GraphQL support
pip install graphql-complexity[strawberry-graphql]

Quick Start

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
    }
""")

complexity = get_complexity(
    query="query { user { id name } }",
    schema=schema,
    estimator=SimpleEstimator(complexity=1),
)

if complexity > 10:
    raise Exception(f"Query is too complex: {complexity}")

Estimators

Estimator Description
SimpleEstimator Assigns a constant cost to every field
DirectivesEstimator Reads cost from @complexity(value: N) schema directives
ArgumentsEstimator Multiplies cost by a numeric/list argument (e.g. limit, ids)
Custom Subclass ComplexityEstimator and implement get_field_complexity

See the estimators docs for full reference and examples.

Integrations

See the integrations docs for examples about how this library integrates with strawberry, FastAPI, Flask and graphene-django.

Credits

Estimators idea was heavily inspired by graphql-query-complexity.

License

MIT

About

Python library to compute the complexity of a GraphQL operation

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Contributors

Languages