Schemathesis

4.15.0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to load an OpenAPI schema from a URI and then execute property-based tests against a live API endpoint using `schemathesis.test()`. It includes notes on specifying the API base URL and handling authentication.

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)

view raw JSON →