Schemathesis
Schemathesis is a property-based testing framework for API specifications, primarily OpenAPI and GraphQL. It generates test cases from your schema, fuzzing inputs to find edge cases and ensure API contracts are met. Currently at version 4.15.0, it maintains an active release schedule with frequent updates and improvements.
Warnings
- breaking The `schema.validate_response()` method for running tests was removed in Schemathesis v4. It has been replaced by `schema.test()`.
- breaking The signatures for `schemathesis.from_asgi()` and `schemathesis.from_wsgi()` changed significantly in v4. The `app` parameter for the ASGI/WSGI application was renamed to `app_or_path` and its behavior was refined.
- gotcha Authentication for your API under test is often overlooked. Schemathesis by default sends requests without authentication, leading to 401/403 errors and incomplete test coverage.
- gotcha The `base_url` parameter for `schema.test()` is critical. If not specified correctly, tests might be sent to the wrong endpoint, or if your schema lacks a `servers` field, requests might fail entirely.
Install
-
pip install schemathesis -
pip install schemathesis[fastapi] -
pip install schemathesis[flask]
Imports
- from_uri
import schemathesis; schema = schemathesis.from_uri(...)
- from_dict
import schemathesis; schema = schemathesis.from_dict(...)
- test
result = schema.test(base_url='...')
- register_check
import schemathesis; @schemathesis.register_check('my_check') def my_check_function(...): ...
Quickstart
import schemathesis
import os
# For this example, we use a public OpenAPI spec and a public API endpoint.
# In a real scenario, SCHEMA_URL would be your API's spec and API_BASE_URL
# would be the target environment (e.g., 'http://localhost:8000').
SCHEMA_URL = "https://petstore.swagger.io/v2/swagger.json"
API_BASE_URL = "https://petstore.swagger.io/v2"
# Optional: Configure authentication if your API requires it.
# For example, with an API key in a header:
# AUTH_HEADER_KEY = os.environ.get('MY_API_KEY_HEADER', '')
# AUTH_HEADER_VALUE = os.environ.get('MY_API_KEY_VALUE', '')
# custom_headers = {AUTH_HEADER_KEY: AUTH_HEADER_VALUE} if AUTH_HEADER_KEY else {}
try:
# Load the API schema from a URI
schema = schemathesis.from_uri(SCHEMA_URL)
# Run the tests against the live API.
# The `base_url` parameter is crucial to specify the actual API endpoint
# where requests will be sent. Add `headers=custom_headers` for auth.
result = schema.test(base_url=API_BASE_URL)
if result.is_success:
print("\nAll Schemathesis tests passed successfully!")
else:
print("\nSchemathesis tests failed. See report for details.")
# Uncomment the line below for a detailed failure report
# print(result.to_json())
exit(1) # Indicate failure in a script context
except Exception as e:
print(f"\nAn error occurred during testing: {e}")
exit(1)