Skip to main content

Semblance

CI PyPI version Documentation status Python versions Ruff License: MIT

Build a REST API simulator from Pydantic models.

Semblance turns request and response schemas into a running FastAPI app. Use field metadata to bind responses to request data, generate values within constraints, and simulate failures—without writing endpoint logic.

Build against a mock while the backend takes shape, exercise a client's retry behavior, or run integration tests with repeatable data. FastAPI handles request validation and OpenAPI; Polyfactory generates the response data.

Documentation · Capper example · Inputs and outputs · Changelog · Contributing

Quick start

Requires Python 3.10+. FastAPI, Pydantic, Polyfactory, and Uvicorn are installed with Semblance.

pip install semblance

Save this as app.py:

from datetime import date, datetime
from typing import Annotated

from pydantic import BaseModel
from semblance import DateRangeFrom, FromInput, SemblanceAPI


class UserQuery(BaseModel):
    name: str = "alice"
    start_date: date = date(2024, 1, 1)
    end_date: date = date(2024, 12, 31)


class User(BaseModel):
    name: Annotated[str, FromInput("name")]
    created_at: Annotated[datetime, DateRangeFrom("start_date", "end_date")]


api = SemblanceAPI(seed=42)


@api.get("/users", input=UserQuery, output=list[User], list_count=2)
def users():
    pass


app = api.as_fastapi()

Start the simulator:

semblance run app:api --port 8000

Input — in another terminal:

curl "http://127.0.0.1:8000/users?name=alice"

Output — 200 OK:

[
  {"name": "alice", "created_at": "2024-08-22T00:43:29.352128"},
  {"name": "alice", "created_at": "2024-01-10T03:41:40.080943"}
]

Change name, start_date, or end_date in the query to change the response. Explore the interactive API docs at localhost:8000/docs or fetch the schema at /openapi.json. You can also serve the exported app with uvicorn app:app --reload.

How it works

  1. Describe the request. An input model defines query, path, or body fields and their Pydantic validation rules.
  2. Describe the response. An output model defines the response shape. Polyfactory generates fields; Annotated links supply values from inputs, other fields, headers, cookies, or JSON fixtures.
  3. Choose the behavior. Route options control list size, pagination, errors, timing, and authentication. A fixed seed makes generated data repeatable.

In the quick start, FromInput("name") copies the requested name and DateRangeFrom(...) generates timestamps within the requested range. The function body is a registration placeholder; Semblance ignores it and generates the response from the models.

Register GET, POST, PUT, PATCH, and DELETE routes with the same pattern. Return a model, list[Model], or a pagination wrapper; DELETE with output=None returns 204 No Content.

Generate realistic data with Capper

Capper adds semantic types such as Name, Email, Company, and City. Use them in your output model and Semblance's Polyfactory integration automatically generates values with the corresponding Faker providers.

Install the optional dependency:

pip install "capper[pydantic]"

Save this as realistic.py:

from typing import Annotated

from capper import City, Company, Email, Name
from pydantic import BaseModel
from semblance import FromInput, SemblanceAPI


class CustomerQuery(BaseModel):
    segment: str = "trial"
    seed: int = 42


class Customer(BaseModel):
    name: Name
    email: Email
    company: Company
    city: City
    segment: Annotated[str, FromInput("segment")]


api = SemblanceAPI()


@api.get("/customer", input=CustomerQuery, output=Customer, seed_from="seed")
def customer():
    pass

Run semblance run realistic:api --port 8002.

Input:

curl "http://127.0.0.1:8002/customer?segment=enterprise&seed=42"

Output — 200 OK:

{
  "name": "Allison Hill",
  "email": "donaldgarcia@example.net",
  "company": "Miller, Henderson and Johnson",
  "city": "East William",
  "segment": "enterprise"
}

The query supplies segment; Capper generates the other fields. Change seed to generate another customer, or repeat it for the same result with the same dependency versions. This response was captured with Capper 1.1.1, Faker 40.43.0, and Polyfactory 3.5.0. Capper fields are generated independently; use ComputedFrom or custom links when fields need to depend on one another.

Test without a server

Install the test dependencies:

pip install pytest httpx2 "fastapi>=0.133.0" "starlette>=1.3.1"

Save this beside app.py as test_app.py:

from datetime import datetime

from app import app
from semblance import test_client as make_test_client


def test_users():
    with make_test_client(app) as client:
        response = client.get("/users", params={"name": "testuser"})

    assert response.status_code == 200
    users = response.json()
    assert len(users) == 2
    assert all(user["name"] == "testuser" for user in users)
    assert all(
        datetime(2024, 1, 1)
        <= datetime.fromisoformat(user["created_at"])
        < datetime(2025, 1, 1)
        for user in users
    )

The input is GET /users?name=testuser. The test client calls the app in process and receives 200 OK with:

[
  {"name": "testuser", "created_at": "2024-08-22T00:43:29.352128"},
  {"name": "testuser", "created_at": "2024-01-10T03:41:40.080943"}
]

Run pytest -q test_app.py. The result is 1 passed (timing varies). Use seed_from="seed" on a route to take a per-request seed from an input field, or add Hypothesis for property-based tests.

Simulate failure and recovery

Test a client that should recover after a temporary outage. Save this as resilience.py, reusing the models from app.py:

from app import User, UserQuery
from semblance import ScenarioStep, SemblanceAPI

api = SemblanceAPI(seed=42)


@api.get(
    "/users",
    input=UserQuery,
    output=list[User],
    list_count=2,
    scenario=(
        ScenarioStep(status=503, detail="Temporarily unavailable"),
        ScenarioStep(status=200),
    ),
)
def users():
    pass

Run semblance run resilience:api --port 8001.

First input:

curl "http://127.0.0.1:8001/users?name=alice"

Output — 503 Service Unavailable:

{"detail": "Temporarily unavailable"}

Second input — repeat the same request:

curl "http://127.0.0.1:8001/users?name=alice"

Output — 200 OK:

[
  {"name": "alice", "created_at": "2024-08-22T00:43:29.352128"},
  {"name": "alice", "created_at": "2024-01-10T03:41:40.080943"}
]

Subsequent requests also return generated users. Each route holds its final scenario step until the simulator is restarted.

For other failure modes, use ErrorCase to match validated input, error_rate and error_codes for random failures, or latency_ms, jitter_ms, and rate_limit to exercise slow requests and throttling. See simulation options.

Capabilities

Need Semblance provides
Bind responses to requests FromInput, FromHeader, and FromCookie
Express field relationships DateRangeFrom, WhenInput, and ComputedFrom, including nested models
Reuse fixture data FromJsonFixture and FromNestedFixture, with variants and optional strict matching
Generate repeatable data Global seed or per-request seed_from; fixed or input-driven list_count
Page through results PageParams / PaginatedResponse[T] for offset pagination; PageTable / PageSlice[T] for token-keyed pages
Keep state across requests SemblanceAPI(stateful=True) stores POST results for list, lookup, PUT, PATCH, and DELETE routes
Exercise failure handling ErrorCase, ScenarioStep, random errors, latency, jitter, and rate limits
Simulate protected routes A per-route bearer_tokens allow-list; invalid or missing tokens return 401
Validate contracts Pydantic request validation, optional validate_responses=True and validate_links=True, and OpenAPI export
Integrate with existing apps as_fastapi(), mount_into(...), and middleware support
Extend generation and testing Custom links via register_link, pytest fixtures, and Hypothesis helpers

State and rate limits live in memory within a process. Use stateful mode for local workflows and tests; restarting the simulator clears its store. See the stateful CRUD example for a complete create, read, update, and delete flow.

CLI

Use the CLI to scaffold, validate, serve, and export a simulator:

# Create app.py and semblance.yaml in a new project directory
semblance init --with-config

# Check route definitions and field links without starting a server
semblance validate app:api

# Serve with automatic reload during development
semblance run app:app --port 8000 --reload

# Export OpenAPI, including generated response examples
semblance export openapi app:api --examples -o openapi.json

# Export OpenAPI and JSON response fixtures
semblance export fixtures app:api -o fixtures
Command Output or result
semblance init --with-config Writes app.py and semblance.yaml, printing their absolute paths and a run command
semblance validate app:api Prints OK and exits with status 0 when the routes and links are valid
semblance run app:app --port 8000 --reload Starts the simulator at http://127.0.0.1:8000; /docs shows the registered routes
semblance export openapi app:api --examples -o openapi.json Prints Wrote openapi.json; the file contains the /users schema and example responses
semblance export fixtures app:api -o fixtures Prints Wrote fixtures to fixtures; the directory contains OpenAPI and JSON response fixtures

See the CLI guide for all options and the concepts guide for configuration defaults.

Examples

From a clone of this repository, run an example with:

semblance run examples.basic.app:api --port 8000

Replace basic with any module below:

Module Demonstrates
basic Input bindings and generated date ranges
pagination Paginated response models
nested Links in nested models
advanced Conditional links, computed fields, and filtering
stateful Store created items and list them
stateful_crud Full CRUD with an in-memory store
put_patch_delete Generated PUT, PATCH, and DELETE responses
error_simulation Seeded success, 404, and 503 responses
request_links Header and cookie bindings
plugins Custom link types

Expand an example below for its inputs and captured outputs. Start one example server at a time on port 8000. Generated values can change with dependency versions; use the IDs returned by your running server when following a stateful sequence.

basic — input bindings and date ranges

Source · Guide

Input:

curl -sS 'http://127.0.0.1:8000/users?name=alice&start_date=2024-01-01&end_date=2024-12-31'

Output — 200 OK:

[
  {"name": "alice", "created_at": "2024-08-22T00:43:29.352128"},
  {"name": "alice", "created_at": "2024-01-10T03:41:40.080943"}
]
pagination — limit, offset, and total

Source · Guide

This example generates a pool of limit items, so limit=3 and offset=0 return three items with total=3.

Input:

curl -sS 'http://127.0.0.1:8000/users?limit=3&offset=0&name=alice'

Output — 200 OK:

{
  "items": [
    {
      "name": "alice"
    },
    {
      "name": "alice"
    },
    {
      "name": "alice"
    }
  ],
  "total": 3,
  "limit": 3,
  "offset": 0
}
nested — request data inside a nested response

Source · Guide

The city is bound to the request. This module uses plain str fields for street and ZIP; the Capper example above demonstrates how semantic types improve generated data.

Input:

curl -sS 'http://127.0.0.1:8000/user?name=foo&city=Boston'

Output — 200 OK:

{
  "name": "foo",
  "address": {
    "street": "HbolMJUevblAbkHClEQa",
    "city": "Boston",
    "zip": "PKriXrefSFPLBYtCRGSE"
  }
}
advanced — conditional, computed, and filtered fields

Source · Guide

Input 1:

curl -sS 'http://127.0.0.1:8000/user/status?name=alice&include_status=true&status=active'

Output — 200 OK:

{"name": "alice", "status": "active"}

Input 2:

curl -sS 'http://127.0.0.1:8000/user/fullname?first=Jane&last=Smith'

Output — 200 OK:

{"first": "Jane", "last": "Smith", "full": "Jane Smith"}

Input 3:

curl -sS 'http://127.0.0.1:8000/users?name=x&status=active&include_status=true'

Output — 200 OK:

[
  {"name": "x", "status": "active"},
  {"name": "x", "status": "active"},
  {"name": "x", "status": "active"}
]
stateful — create an item, then list stored items

Source · Guide

Run against a fresh server, in the order shown. Generated IDs can vary; the same ID appears in the stored list.

Input 1:

curl -sS -X POST http://127.0.0.1:8000/users -H 'Content-Type: application/json' -d '{"name": "alice"}'

Output — 200 OK:

{"id": "HbolMJUevblAbkHClEQa", "name": "alice"}

Input 2:

curl -sS http://127.0.0.1:8000/users

Output — 200 OK:

[
  {"id": "HbolMJUevblAbkHClEQa", "name": "alice"}
]
stateful_crud — create, read, replace, patch, list, and delete

Source · Guide

Run against a fresh server, in the order shown. Use the ID returned by POST in subsequent paths; the sample below uses HbolMJUevblAbkHClEQa.

Input 1:

curl -sS -X POST http://127.0.0.1:8000/users -H 'Content-Type: application/json' -d '{"name": "alice"}'

Output — 200 OK:

{"id": "HbolMJUevblAbkHClEQa", "name": "alice"}

Input 2:

curl -sS http://127.0.0.1:8000/users/HbolMJUevblAbkHClEQa

Output — 200 OK:

{"id": "HbolMJUevblAbkHClEQa", "name": "alice"}

Input 3:

curl -sS -X PUT http://127.0.0.1:8000/users/HbolMJUevblAbkHClEQa -H 'Content-Type: application/json' -d '{"name": "alice-replaced"}'

Output — 200 OK:

{"id": "HbolMJUevblAbkHClEQa", "name": "alice-replaced"}

Input 4:

curl -sS -X PATCH http://127.0.0.1:8000/users/HbolMJUevblAbkHClEQa -H 'Content-Type: application/json' -d '{"name": "alice-updated"}'

Output — 200 OK:

{"id": "HbolMJUevblAbkHClEQa", "name": "alice-updated"}

Input 5:

curl -sS http://127.0.0.1:8000/users

Output — 200 OK:

[
  {"id": "HbolMJUevblAbkHClEQa", "name": "alice-updated"}
]

Input 6:

curl -sS -X DELETE http://127.0.0.1:8000/users/HbolMJUevblAbkHClEQa

Output — 204 No Content:

No response body.

Input 7:

curl -sS http://127.0.0.1:8000/users/HbolMJUevblAbkHClEQa

Output — 404 Not Found:

{"detail": "Not found"}
put_patch_delete — generated responses for write methods

Source · Guide

These routes generate responses without storing them. The output id is a generated string, so it does not echo the path ID.

Input 1:

curl -sS -X PUT http://127.0.0.1:8000/users/abc -H 'Content-Type: application/json' -d '{"name": "put-user"}'

Output — 200 OK:

{"id": "HbolMJUevblAbkHClEQa", "name": "put-user"}

Input 2:

curl -sS -X PATCH http://127.0.0.1:8000/users/xyz -H 'Content-Type: application/json' -d '{"name": "patch-user"}'

Output — 200 OK:

{"id": "HbolMJUevblAbkHClEQa", "name": "patch-user"}

Input 3:

curl -sS -X DELETE http://127.0.0.1:8000/users/123

Output — 204 No Content:

No response body.

Input 4:

curl -sS -X DELETE http://127.0.0.1:8000/users/123/with-body

Output — 200 OK:

{"id": "HbolMJUevblAbkHClEQa", "name": "PKriXrefSFPLBYtCRGSE"}
error_simulation — successful and failing responses

Source · Guide

With the bundled SemblanceAPI(seed=99), this request consistently succeeds. The other fixed seeds below reproduce the configured failure responses. To sample failures across repeated requests, use SemblanceAPI() without a fixed seed.

Input 1:

curl -sS 'http://127.0.0.1:8000/users?name=alice'

Output — 200 OK:

[
  {"name": "alice"},
  {"name": "alice"}
]

For this input, restart the example after changing its constructor to SemblanceAPI(seed=1).

Input 2:

curl -sS 'http://127.0.0.1:8000/users?name=alice'

Output — 404 Not Found:

{"detail": "Simulated error"}

For this input, restart the example after changing its constructor to SemblanceAPI(seed=8).

Input 3:

curl -sS 'http://127.0.0.1:8000/users?name=alice'

Output — 503 Service Unavailable:

{"detail": "Simulated error"}
request_links — query, header, and cookie inputs

Source · Guide

Input:

curl -sS 'http://127.0.0.1:8000/user?name=alice' -H 'X-Request-Id: id-1' -H 'Cookie: session_id=sess-1'

Output — 200 OK:

{"name": "alice", "request_id": "id-1", "session": "sess-1"}
plugins — environment data and a custom link

Source · Guide

Start this module with its environment input set:

USER_NAME=DocBot semblance run examples.plugins.app:api --port 8000

Input:

curl -sS 'http://127.0.0.1:8000/user?role=admin'

Output — 200 OK:

{"name": "DocBot", "role": "admin"}

Optional API adapters

Separate packages simulate selected operations of external APIs using bundled or custom fixtures:

Package Coverage Install
semblance-foundry Selected Foundry API v2 ontology-read operations pip install semblance-foundry
semblance-databricks Selected Databricks workspace REST operations pip install semblance-databricks

Both adapters are unofficial, independently versioned test doubles. Their package READMEs document supported operations, authentication modes, and compatibility limits.

Documentation

Start with Getting started or choose a guide:

Development

Set up all three packages from a clean clone:

git clone https://github.com/eddiethedean/semblance.git
cd semblance
python -m venv .venv
source .venv/bin/activate
# Windows: .venv\Scripts\activate
pip install -e ".[dev]"
pip install -e "packages/semblance-foundry[dev]"
pip install -e "packages/semblance-databricks[dev]"

pytest tests/ -v -m "not sdk"
pytest packages/semblance-foundry/tests -v -m "not sdk"
pytest packages/semblance-databricks/tests -v -m "not sdk"

See CONTRIBUTING.md for lint, type, security, and documentation checks. Report vulnerabilities through the process in SECURITY.md.

License

MIT.

Metadata

Release files for semblance 0.9.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for semblance 0.9.2
File Size Uploaded Provenance Actions
semblance-0.9.2.tar.gz 64.1 kB Without provenance Details for semblance-0.9.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for semblance 0.9.2
File Interpreter ABI Platform Actions
semblance-0.9.2-py3-none-any.whl Python 3 none any Details for semblance-0.9.2-py3-none-any.whl

Total release size: 106.5 kB

Release files / semblance-0.9.2.tar.gz

Download URL semblance-0.9.2.tar.gz
Size 64.1 kB
Tags Source
SHA-256 checksum
How to use checksums
17bc143778f27afaaf4eae996a5d0e3eafa79175465c787d14b76640f975ad6d
BLAKE2b-256 checksum
How to use checksums
925b70bfbe7493982c96e4527fd38f76e7e38ee0848a026a6648c6c3d33141a7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / semblance-0.9.2-py3-none-any.whl

Download URL semblance-0.9.2-py3-none-any.whl
Size 42.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e91c7b4271c29b3de38fc04bd43d75324bbd5b2b7ea3604e3c3e9017e661c55e
BLAKE2b-256 checksum
How to use checksums
d97ede405c272e55a13fb3eafac9976a3e51d52a459f67f0a8dbd25eec44c775
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for semblance 0.9.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page