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
pip install graphql-complexity
# With Strawberry GraphQL support
pip install graphql-complexity[strawberry-graphql]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}")| 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.
See the integrations docs for examples
about how this library integrates with strawberry, FastAPI, Flask and graphene-django.
Estimators idea was heavily inspired by graphql-query-complexity.
