Public API reference

Checks

schemathesis.register_check(function: Callable[[Union[requests.models.Response, schemathesis.utils.WSGIResponse], schemathesis.models.Case], Optional[bool]])Callable[[Union[requests.models.Response, schemathesis.utils.WSGIResponse], schemathesis.models.Case], Optional[bool]][source]

Register a new check for schemathesis CLI.

Parameters

function – A function to validate API responses.

@schemathesis.register_check
def new_check(response, case):
    # some awesome assertions!
    ...

Fixups

Available fixups:

  • fast_api

schemathesis.fixups.install(fixups: Optional[Iterable[str]] = None)None[source]

Install fixups.

Without the first argument installs all available fixups.

Parameters

fixups – Names of fixups to install.

schemathesis.fixups.uninstall(fixups: Optional[Iterable[str]] = None)None[source]

Uninstall fixups.

Without the first argument uninstalls all available fixups.

Parameters

fixups – Names of fixups to uninstall.

Hooks

class schemathesis.hooks.HookContext(operation: Optional[APIOperation] = None)[source]

A context that is passed to some hook functions.

Variables

operation (Optional[APIOperation]) – API operation that is currently being processed. Might be absent in some cases.

These functions affect Schemathesis behavior globally:

schemathesis.hooks.register(hook: Union[str, Callable])Callable

Register a new hook.

Parameters

hook – Either a hook function or a string.

Can be used as a decorator in two forms. Without arguments for registering hooks and autodetecting their names:

@schemathesis.hooks.register
def before_generate_query(context, strategy):
    ...

With a hook name as the first argument:

@schemathesis.hooks.register("before_generate_query")
def hook(context, strategy):
    ...
schemathesis.hooks.unregister(hook: Callable)None

Unregister a specific hook.

Parameters

hook – A hook function to unregister.

schemathesis.hooks.unregister_all()None

Remove all registered hooks.

Useful in tests.

class schemathesis.schemas.BaseSchema

All functions above can be accessed via schema.hooks.<function-name> on a schema instance. Such calls will affect only tests generated from the schema instance. Additionally you can use the following:

schema.hooks.apply()

Register hook to run only on one test function.

Parameters
  • hook – A hook function.

  • name (Optional[str]) – A hook name.

def before_generate_query(context, strategy):
    ...


@schema.hooks.apply(before_generate_query)
@schema.parametrize()
def test_api(case):
    ...

Serializers

class schemathesis.serializers.SerializerContext(case: Case)[source]

The context for serialization process.

Variables

case (Case) – Generated example that is being processed.

schemathesis.serializers.register(media_type: str, *, aliases: Collection[str] = ())Callable[[Type[schemathesis.serializers.Serializer]], Type[schemathesis.serializers.Serializer]][source]

Register a serializer for the given media type.

Schemathesis uses requests for regular network calls and werkzeug for WSGI applications. Your serializer should have two methods, as_requests and as_werkzeug, providing keyword arguments that Schemathesis will pass to requests.request and werkzeug.Client.open respectively.

@register("text/csv")
class CSVSerializer:
    def as_requests(self, context, value):
        return {"data": to_csv(value)}

    def as_werkzeug(self, context, value):
        return {"data": to_csv(value)}

The primary purpose of serializers is to transform data from its Python representation to the format suitable for making an API call. The generated data structure depends on your schema, but its type matches Python equivalents to the JSON Schema types.

schemathesis.serializers.unregister(media_type: str)None[source]

Remove registered serializer for the given media type.

Targeted testing

class schemathesis.targets.TargetContext(case: Case, response: Union[requests.models.Response, schemathesis.utils.WSGIResponse], response_time: float)[source]

Context for targeted testing.

Variables
  • case (Case) – Generated example that is being processed.

  • response (GenericResponse) – API response.

  • response_time (float) – API response time.

schemathesis.register_target(function: Callable[[schemathesis.targets.TargetContext], float])Callable[[schemathesis.targets.TargetContext], float][source]

Register a new testing target for schemathesis CLI.

Parameters

function – A function that will be called to calculate a metric passed to hypothesis.target.

Custom strategies for Open API “format” keyword

schemathesis.register_string_format(name: str, strategy: hypothesis.strategies.SearchStrategy)None[source]

Register a new strategy for generating data for specific string “format”.

Parameters
  • name (str) – Format name. It should correspond the one used in the API schema as the “format” keyword value.

  • strategy – Hypothesis strategy you’d like to use to generate values for this format.

Loaders

schemathesis.from_aiohttp(schema_path: str, app: Any, *, base_url: Optional[str] = None, method: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, endpoint: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, tag: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, operation_id: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, skip_deprecated_operations: bool = False, validate_schema: bool = True, force_schema_version: Optional[str] = None, data_generation_methods: Union[DataGenerationMethod, Iterable[DataGenerationMethod]] = (<DataGenerationMethod.positive: 'positive'>,), code_sample_style: str = 'curl', **kwargs: Any)schemathesis.specs.openapi.schemas.BaseOpenAPISchema[source]

Load Open API schema from an AioHTTP app.

Parameters
  • schema_path (str) – An in-app relative URL to the schema.

  • app – An AioHTTP app instance.

schemathesis.from_asgi(schema_path: str, app: Any, *, base_url: Optional[str] = None, method: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, endpoint: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, tag: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, operation_id: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, skip_deprecated_operations: bool = False, validate_schema: bool = True, force_schema_version: Optional[str] = None, data_generation_methods: Union[DataGenerationMethod, Iterable[DataGenerationMethod]] = (<DataGenerationMethod.positive: 'positive'>,), code_sample_style: str = 'curl', **kwargs: Any)schemathesis.specs.openapi.schemas.BaseOpenAPISchema[source]

Load Open API schema from an ASGI app.

Parameters
  • schema_path (str) – An in-app relative URL to the schema.

  • app – An ASGI app instance.

schemathesis.from_dict(raw_schema: Dict[str, Any], *, app: Any = None, base_url: Optional[str] = None, method: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, endpoint: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, tag: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, operation_id: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, skip_deprecated_operations: bool = False, validate_schema: bool = True, force_schema_version: Optional[str] = None, data_generation_methods: Union[DataGenerationMethod, Iterable[DataGenerationMethod]] = (<DataGenerationMethod.positive: 'positive'>,), code_sample_style: str = 'curl', location: Optional[str] = None)schemathesis.specs.openapi.schemas.BaseOpenAPISchema[source]

Load Open API schema from a Python dictionary.

Parameters

raw_schema (dict) – A schema to load.

schemathesis.from_file(file: Union[IO[str], str], *, app: Any = None, base_url: Optional[str] = None, method: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, endpoint: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, tag: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, operation_id: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, skip_deprecated_operations: bool = False, validate_schema: bool = True, force_schema_version: Optional[str] = None, data_generation_methods: Union[DataGenerationMethod, Iterable[DataGenerationMethod]] = (<DataGenerationMethod.positive: 'positive'>,), code_sample_style: str = 'curl', location: Optional[str] = None, **kwargs: Any)schemathesis.specs.openapi.schemas.BaseOpenAPISchema[source]

Load Open API schema from a file descriptor, string or bytes.

Parameters

file – Could be a file descriptor, string or bytes.

schemathesis.from_path(path: Union[pathlib.Path, str], *, app: Any = None, base_url: Optional[str] = None, method: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, endpoint: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, tag: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, operation_id: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, skip_deprecated_operations: bool = False, validate_schema: bool = True, force_schema_version: Optional[str] = None, data_generation_methods: Union[DataGenerationMethod, Iterable[DataGenerationMethod]] = (<DataGenerationMethod.positive: 'positive'>,), code_sample_style: str = 'curl', encoding: str = 'utf8')schemathesis.specs.openapi.schemas.BaseOpenAPISchema[source]

Load Open API schema via a file from an OS path.

Parameters
  • path – A path to the schema file.

  • encoding – The name of the encoding used to decode the file.

schemathesis.from_pytest_fixture(fixture_name: str, *, app: Any = <schemathesis.types.NotSet object>, base_url: Union[str, None, schemathesis.types.NotSet] = <schemathesis.types.NotSet object>, method: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = <schemathesis.types.NotSet object>, endpoint: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = <schemathesis.types.NotSet object>, tag: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = <schemathesis.types.NotSet object>, operation_id: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = <schemathesis.types.NotSet object>, skip_deprecated_operations: bool = False, validate_schema: bool = True, data_generation_methods: Union[DataGenerationMethod, Iterable[DataGenerationMethod], schemathesis.types.NotSet] = <schemathesis.types.NotSet object>, code_sample_style: str = 'curl')schemathesis.lazy.LazySchema[source]

Load schema from a pytest fixture.

It is useful if you don’t want to make network requests during module loading. With this loader you can defer it to a fixture.

Note, the fixture should return a BaseSchema instance loaded with another loader.

Parameters

fixture_name (str) – The name of a fixture to load.

schemathesis.from_uri(uri: str, *, app: Any = None, base_url: Optional[str] = None, port: Optional[int] = None, method: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, endpoint: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, tag: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, operation_id: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, skip_deprecated_operations: bool = False, validate_schema: bool = True, force_schema_version: Optional[str] = None, data_generation_methods: Union[DataGenerationMethod, Iterable[DataGenerationMethod]] = (<DataGenerationMethod.positive: 'positive'>,), code_sample_style: str = 'curl', **kwargs: Any)schemathesis.specs.openapi.schemas.BaseOpenAPISchema[source]

Load Open API schema from the network.

Parameters

uri (str) – Schema URL.

schemathesis.from_wsgi(schema_path: str, app: Any, *, base_url: Optional[str] = None, method: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, endpoint: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, tag: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, operation_id: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = None, skip_deprecated_operations: bool = False, validate_schema: bool = True, force_schema_version: Optional[str] = None, data_generation_methods: Union[DataGenerationMethod, Iterable[DataGenerationMethod]] = (<DataGenerationMethod.positive: 'positive'>,), code_sample_style: str = 'curl', **kwargs: Any)schemathesis.specs.openapi.schemas.BaseOpenAPISchema[source]

Load Open API schema from a WSGI app.

Parameters
  • schema_path (str) – An in-app relative URL to the schema.

  • app – A WSGI app instance.

schemathesis.graphql.from_dict(raw_schema: Dict[str, Any], *, app: Any = None, base_url: Optional[str] = None, location: Optional[str] = None, data_generation_methods: Union[DataGenerationMethod, Iterable[DataGenerationMethod]] = (<DataGenerationMethod.positive: 'positive'>,), code_sample_style: str = 'curl')schemathesis.specs.graphql.schemas.GraphQLSchema

Load GraphQL schema from a Python dictionary.

Parameters
  • raw_schema (dict) – A schema to load.

  • location (Optional[str]) – Optional schema location. Either a full URL or a filesystem path.

  • base_url (Optional[str]) – Base URL to send requests to.

  • app – A WSGI app instance.

Returns

GraphQLSchema

schemathesis.graphql.from_url(url: str, *, app: Any = None, base_url: Optional[str] = None, port: Optional[int] = None, data_generation_methods: Union[DataGenerationMethod, Iterable[DataGenerationMethod]] = (<DataGenerationMethod.positive: 'positive'>, ), code_sample_style: str = 'curl', **kwargs: Any)schemathesis.specs.graphql.schemas.GraphQLSchema

Load GraphQL schema from the network.

Parameters
  • url – Schema URL.

  • base_url (Optional[str]) – Base URL to send requests to.

  • port (Optional[int]) – An optional port if you don’t want to pass the base_url parameter, but only to change port in url.

  • app – A WSGI app instance.

Returns

GraphQLSchema

schemathesis.graphql.from_wsgi(schema_path: str, app: Any, *, base_url: Optional[str] = None, data_generation_methods: Union[DataGenerationMethod, Iterable[DataGenerationMethod]] = (<DataGenerationMethod.positive: 'positive'>, ), code_sample_style: str = 'curl', **kwargs: Any)schemathesis.specs.graphql.schemas.GraphQLSchema

Load GraphQL schema from a WSGI app.

Parameters
  • schema_path (str) – An in-app relative URL to the schema.

  • app – A WSGI app instance.

  • base_url (Optional[str]) – Base URL to send requests to.

Returns

GraphQLSchema

Schema

class schemathesis.schemas.BaseSchema[source]
parametrize(method: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = <schemathesis.types.NotSet object>, endpoint: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = <schemathesis.types.NotSet object>, tag: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = <schemathesis.types.NotSet object>, operation_id: Optional[Union[str, List[str], Tuple[str], Set[str], schemathesis.types.NotSet]] = <schemathesis.types.NotSet object>, validate_schema: Union[bool, schemathesis.types.NotSet] = <schemathesis.types.NotSet object>, skip_deprecated_operations: Union[bool, schemathesis.types.NotSet] = <schemathesis.types.NotSet object>, data_generation_methods: Union[Iterable[schemathesis.constants.DataGenerationMethod], schemathesis.types.NotSet] = <schemathesis.types.NotSet object>, code_sample_style: Union[str, schemathesis.types.NotSet] = <schemathesis.types.NotSet object>)Callable[source]

Mark a test function as a parametrized one.

given(*args: Union[hypothesis.strategies.SearchStrategy, hypothesis.utils.conventions.InferType], **kwargs: Union[hypothesis.strategies.SearchStrategy, hypothesis.utils.conventions.InferType])Callable[source]

Proxy Hypothesis strategies to hypothesis.given.

as_state_machine()Type[schemathesis.stateful.APIStateMachine][source]

Create a state machine class.

Use it for stateful testing.

class schemathesis.models.APIOperation[source]

A single operation defined in an API.

You can get one via a schema instance.

# Get the POST /items operation
operation = schema["/items"]["POST"]
Members

validate_response(response: Union[requests.models.Response, schemathesis.utils.WSGIResponse])None[source]

Validate API response for conformance.

Raises

CheckFailed – If the response does not conform to the API schema.

is_response_valid(response: Union[requests.models.Response, schemathesis.utils.WSGIResponse])bool[source]

Validate API response for conformance.

make_case(*, path_parameters: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, Any]] = None, cookies: Optional[Dict[str, Any]] = None, query: Optional[Dict[str, Any]] = None, body: Union[List, Dict[str, Any], str, int, float, bool, bytes, schemathesis.types.NotSet] = <schemathesis.types.NotSet object>, media_type: Optional[str] = None)C[source]

Create a new example for this API operation.

The main use case is constructing Case instances completely manually, without data generation.

as_strategy(hooks: Optional[schemathesis.hooks.HookDispatcher] = None, data_generation_method: schemathesis.constants.DataGenerationMethod = <DataGenerationMethod.positive: 'positive'>)hypothesis.strategies.SearchStrategy[source]

Turn this API operation into a Hypothesis strategy.

Open API-specific API

class schemathesis.specs.openapi.schemas.BaseOpenAPISchema[source]
add_link(source: schemathesis.models.APIOperation, target: Union[str, schemathesis.models.APIOperation], status_code: Union[str, int], parameters: Optional[Dict[str, str]] = None, request_body: Optional[Any] = None)None[source]

Add a new Open API link to the schema definition.

Parameters
  • source (APIOperation) – This operation is the source of data

  • target – This operation will receive the data from this link. Can be an APIOperation instance or a reference like this - #/paths/~1users~1{userId}/get

  • status_code (str) – The link is triggered when the source API operation responds with this status code.

  • parameters – A dictionary that describes how parameters should be extracted from the matched response. The key represents the parameter name in the target API operation, and the value is a runtime expression string.

  • request_body – A literal value or runtime expression to use as a request body when calling the target operation.

schema = schemathesis.from_uri("http://0.0.0.0/schema.yaml")

schema.add_link(
    source=schema["/users/"]["POST"],
    target=schema["/users/{userId}"]["GET"],
    status_code="201",
    parameters={"userId": "$response.body#/id"},
)