Skip to content

Extending Schemathesis

Customize how Schemathesis generates test data, validates responses, and handles requests through hooks, custom checks, and data generation strategies.

Prerequisites

  • Schemathesis installed or available via uvx
  • A Python file you can load with SCHEMATHESIS_HOOKS (CLI) or a conftest.py (pytest)

Quick Start: Your First Hook

Your API returns 404 for GET /users/{user_id} because generated IDs do not exist. Replace the generated user_id with one that does:

# hooks.py
import schemathesis


@schemathesis.hook
def map_path_parameters(ctx, path_parameters):
    if path_parameters and "user_id" in path_parameters:
        path_parameters["user_id"] = 42
    return path_parameters
export SCHEMATHESIS_HOOKS=hooks
uvx schemathesis run http://localhost:8000/openapi.json

Requests generated in the fuzzing and stateful phases use user_id=42. In the examples phase, component hooks apply only to generated parts and never change values taken from schema examples. The coverage phase does not run map_*/filter_* component hooks, so its requests keep their own user_id values; see phase compatibility.

To pin a value in every phase without code, use a parameter override in schemathesis.toml:

[parameters]
"path.user_id" = 42

To mix known IDs with generated ones instead, bind a fuzz dictionary to the parameter. Dictionary bindings apply in the fuzzing and stateful phases.

Hook Types and Naming

Data generation hooks use a naming pattern: <operation>_<part> where the operation determines what the hook does and the part determines which request data it affects.

Three operations are available:

  • filter_<part> - Skip test cases (return True to keep, False to skip)
  • map_<part> - Transform the drawn value; return the new value
  • flatmap_<part> - Transform the drawn value using additional Hypothesis strategies; return a SearchStrategy

Each operation targets one request part:

  • query - Query parameters
  • headers - HTTP headers
  • path_parameters - URL path parameters
  • cookies - Cookies
  • body - Request body
  • case - The entire test case

Other hooks like before_call, after_call, and before_load_schema have specific names based on when they execute in the testing process.

Data generation hooks apply in this sequence during the fuzzing phase:

filter_* → map_* → flatmap_* → Final test case

Note

Component-level hooks (filter_query, map_headers, and so on) run in the fuzzing and stateful phases. They have no effect in the coverage phase: its cases are built directly and bypass the strategy pipeline where these hooks are applied. See phase compatibility for every hook.

Common Hook Patterns

Filtering unwanted data

Skip test cases that cause known issues or aren't relevant for your API:

@schemathesis.hook
def filter_query(ctx, query):
    if not query:
        return True
    return query.get("user_id") != "admin"

When multiple hooks of the same type are registered, they run in the order they were registered. For filter_* hooks, the case is discarded if any hook returns False - later hooks are not called. For map_* hooks, each receives the output of the previous.

Using real database values

Your API validates IDs against a database, but Schemathesis generates random values that don't exist:

@schemathesis.hook
def map_path_parameters(ctx, path_parameters):
    if path_parameters and "product_id" in path_parameters:
        path_parameters["product_id"] = "product_1"
    return path_parameters

Generating dependent data with flatmap

Use flatmap_<part> when the strategy for one field depends on the value of another - the already-drawn value determines which strategy runs next.

flatmap receives the already-drawn value and must return a SearchStrategy. Hypothesis draws from that strategy to produce the final value.

from hypothesis import strategies as st

SUBCATEGORIES = {
    "electronics": ["phones", "laptops", "tablets"],
    "clothing": ["shirts", "pants", "shoes"],
}


@st.composite
def with_subcategory(draw, body):
    category = (body or {}).get("category")
    options = SUBCATEGORIES.get(category, ["other"])
    subcategory = draw(st.sampled_from(options))
    return {**(body or {}), "subcategory": subcategory}


@schemathesis.hook
def flatmap_body(ctx, body):
    return with_subcategory(body)

The subcategory choices are determined by the generated category - that dependency is why flatmap is needed here. Use map_<part> instead when the transformation is deterministic.

Custom Validation Checks

Function-based checks

A function check receives ctx, response, and case, and raises AssertionError when the response violates an invariant:

@schemathesis.check
def check_user_permissions(ctx, response, case):
    if case.path.startswith("/users/") and response.status_code == 200:
        user_id = case.path_parameters.get("user_id")
        response_data = response.json()
        if response_data.get("id") != user_id:
            actual = response_data.get("id")
            raise AssertionError(f"Accessed wrong data: expected {user_id}, got {actual}")


@schemathesis.check
def check_audit_trail(ctx, response, case):
    if case.method in ("POST", "PUT", "DELETE") and response.status_code < 400:
        if "x-audit-id" not in response.headers:
            raise AssertionError("Data modification missing audit trail")

Header names in response.headers are lowercase, so look them up as "x-audit-id", not "X-Audit-ID".

Class-based checks

When a per-response invariant is not enough, use a class. A class-based check may define:

  • after_response(self, ctx, response, case) - called once per response, same signature as a function check.
  • after_run(self, ctx) - called once after all test phases complete; use it to assert invariants that only make sense across the whole run.

State accumulated in after_response is available in after_run. The CLI creates one instance per run; pytest creates one instance per @schema.parametrize() test function, so its after_run sees only that function's responses.

Warning

after_response may be re-invoked during Hypothesis shrinking and replay. Keep accumulation idempotent - prefer sets and min/max over counters.

pytest-xdist not supported

after_run does not work correctly when tests run with pytest-xdist (-n). Each worker process has its own check instance and sees only its slice of traffic. There is no aggregation across workers, so after_run will observe partial data and may produce false passes or false failures. Avoid after_run checks when using -n.

The built-in not_a_server_error check fails when any response is a 5xx. Sometimes you want a softer invariant: it is acceptable for an endpoint to return occasional errors, but it must succeed at least once during the run:

@schemathesis.check
class EnsureReachability:
    """Fail if any tested operation never returned a 2xx response during the run."""

    def __init__(self):
        self.reached = set()
        self.tested = set()

    def after_response(self, ctx, response, case):
        label = case.operation.label
        self.tested.add(label)
        if 200 <= response.status_code < 300:
            self.reached.add(label)

    def after_run(self, ctx):
        unreachable = self.tested - self.reached
        if unreachable:
            raise AssertionError("never returned 2xx: " + ", ".join(sorted(unreachable)))

Configuring class-based checks

If the check class defines __init__ keyword arguments, Schemathesis forwards matching values from the config file automatically. This lets you tune behaviour per project without changing code:

@schemathesis.check
class EnsureReachability:
    def __init__(self, *, ignore_operations: list[str] | None = None):
        self.ignored = set(ignore_operations or [])
        self.reached = set()
        self.tested = set()

    def after_response(self, ctx, response, case):
        label = case.operation.label
        if label not in self.ignored:
            self.tested.add(label)
            if 200 <= response.status_code < 300:
                self.reached.add(label)

    # after_run is unchanged

Set the value in schemathesis.toml:

[checks.EnsureReachability]
ignore_operations = ["DELETE /health", "GET /ping"]

Any key under [checks.<ClassName>] that matches an __init__ keyword argument is forwarded. Any registered check can also be disabled in the config file:

[checks.EnsureReachability]
enabled = false

Custom Data Formats

from hypothesis import strategies as st

import schemathesis

phone_strategy = st.from_regex(r"\+1-\d{3}-\d{3}-\d{4}")
schemathesis.openapi.format("phone", phone_strategy)

card_strategy = st.from_regex(r"4\d{15}")  # Visa-like format
schemathesis.openapi.format("credit_card", card_strategy)

Now when your schema uses these formats, Schemathesis generates appropriate data:

# In your OpenAPI schema
user_phone:
  type: string
  format: phone  # Uses your custom strategy

Overriding built-in formats

The same API overrides standard formats like date, date-time, uuid, and others. By default Schemathesis generates values across the full valid range - including far-future dates and extreme integers - which is intentional: many server-side bugs only surface when the input isn't sanitised before hitting a database or arithmetic operation. If your application already handles those cases and the out-of-range values are producing noise, restrict the range:

from datetime import date
from hypothesis import strategies as st
import schemathesis

today = date.today()
schemathesis.openapi.format("date", st.dates(max_value=today).map(str))

Setting Up Extensions

# hooks.py (for CLI) or conftest.py (for pytest)
import schemathesis


@schemathesis.hook
def map_headers(ctx, headers):
    if headers is None:
        headers = {}
    headers["X-Test-Mode"] = "true"
    return headers

For CLI usage

export SCHEMATHESIS_HOOKS=hooks
uvx schemathesis run http://localhost:8000/openapi.json

Tip

Two forms are accepted:

  • Module name: SCHEMATHESIS_HOOKS=hooks - imports hooks.py from the current directory or Python path
  • File path: SCHEMATHESIS_HOOKS=hooks.py or SCHEMATHESIS_HOOKS=/path/to/hooks.py - loads the file directly, useful in Docker or CI where the file isn't on the Python path

For pytest integration

Put hooks in conftest.py; pytest imports it before collecting tests, so the hooks apply to every test in that directory:

# conftest.py
import schemathesis


@schemathesis.hook
def map_headers(ctx, headers):
    if headers is None:
        headers = {}
    headers["X-Test-Mode"] = "true"
    return headers
# test_api.py
import schemathesis

schema = schemathesis.openapi.from_url("http://localhost:8000/openapi.json")


@schema.parametrize()
def test_api(case):
    case.call_and_validate()

Targeting Specific Operations

# Only apply to user endpoints, skip POST requests
@schemathesis.hook.apply_to(path_regex=r"/users/").skip_for(method="POST")
def map_headers(ctx, headers):
    headers = headers or {}
    headers["X-User-Context"] = "test-user"
    return headers


# Only apply to a specific operation
@schemathesis.hook.apply_to(name="GET /orders/{order_id}")
def map_path_parameters(ctx, path_parameters):
    path_parameters = path_parameters or {}
    path_parameters["order_id"] = "order_12345"
    return path_parameters

Advanced: Request Modification

before_call runs right before each request is sent, in every phase:

import uuid

import schemathesis


@schemathesis.hook
def before_call(ctx, case, kwargs):
    case.headers["X-Correlation-ID"] = f"test-{uuid.uuid4()}"
    case.query = {**(case.query or {}), "mode": "testing"}

Advanced: Schema Modification Patterns

Remove optional properties to focus tests on required fields only:

@schemathesis.hook
def before_init_operation(ctx, operation):
    for parameter in operation.iter_parameters():
        schema = parameter.definition.get("schema", {})
        remove_optional_properties(schema)

    for alternative in operation.body:
        schema = alternative.definition.get("schema", {})
        remove_optional_properties(schema)


def remove_optional_properties(schema):
    if not isinstance(schema, dict):
        return
    required = schema.get("required", [])
    properties = schema.get("properties", {})
    for name in list(properties.keys()):
        if name not in required:
            del properties[name]
    for subschema in properties.values():
        remove_optional_properties(subschema)

GraphQL Hooks

GraphQL hooks work with graphql.DocumentNode objects instead of JSON data. AST nodes are immutable in graphql-core 3.3+, so build a modified copy with graphql.visit instead of assigning to node attributes.

Modifying GraphQL queries

import graphql

import schemathesis


class RenameField(graphql.Visitor):
    def leave_field(self, node, *_):
        if node.name.value == "oldName":
            return graphql.FieldNode(
                name=graphql.NameNode(value="newName"),
                arguments=node.arguments,
                selection_set=node.selection_set,
            )


@schemathesis.hook
def map_body(ctx, body):
    return graphql.visit(body, RenameField())

Adding URL query parameters

map_query sets query parameters on the request URL, not GraphQL variables:

@schemathesis.hook
def map_query(ctx, query):
    return {"q": "42"}

Schemathesis does not generate query parameters for GraphQL, so query is always None on input.

Filtering GraphQL queries

@schemathesis.hook
def filter_body(ctx, body):
    node = body.definitions[0].selection_set.selections[0]
    return node.name.value != "excludeThisField"

Generating dependent data

This hook adds someDependentField to every query that selects someField:

import graphql
from hypothesis import strategies as st

import schemathesis


class AddDependentField(graphql.Visitor):
    def leave_operation_definition(self, node, *_):
        new_field = graphql.FieldNode(name=graphql.NameNode(value="someDependentField"))
        return graphql.OperationDefinitionNode(
            operation=node.operation,
            name=node.name,
            variable_definitions=node.variable_definitions,
            directives=node.directives,
            selection_set=graphql.SelectionSetNode(selections=(*node.selection_set.selections, new_field)),
        )


@schemathesis.hook
def flatmap_body(ctx, body):
    node = body.definitions[0].selection_set.selections[0]
    if node.name.value == "someField":
        return st.just(graphql.visit(body, AddDependentField()))
    return st.just(body)

For a query { someField }, the request body becomes { someField someDependentField }.

Troubleshooting

The hook never runs. Check that SCHEMATHESIS_HOOKS names the module or file and that it imports without errors. Under pytest, the hooks must be in a conftest.py that pytest collects, or imported before the schema is loaded.

A map_* hook has no effect on some requests. Those requests come from the coverage phase, which does not run map_*/filter_* component hooks, or carry values taken from schema examples, which component hooks never change in the examples phase. Use before_call or a [parameters] override for values that must apply there.

What's Next