Space Python Client
Python client library for Space, a pricing-driven self-adaptation platform for SaaS applications.
Table of Contents
- What You Get
- Requirements
- Installation
- Quick Start in 5 Minutes
- Async Client
- Configuration
- API Overview
- Data Models
- Caching
- WebSocket Events
- Error Handling
- Testing
- Contributing
- License
What You Get
- Simple API to connect to Space.
- An asynchronous client for services that run in an event loop.
- Contract lifecycle operations.
- Feature evaluation with optional expected consumption.
- Revert operation for optimistic usage updates.
- Pricing token generation.
- Built-in in-memory cache and optional Redis cache.
- WebSocket events for real-time pricing updates.
Requirements
- Python 3.10+
Installation
pip install space-python-client
Optional Redis support:
pip install "space-python-client[redis]"
Quick Start in 5 Minutes
from space_client import SpaceClientFactory
client = SpaceClientFactory.connect(
"http://localhost:3000",
"your-api-key",
10_000,
)
healthy = client.is_connected_to_space()
print(f"Connected: {healthy}")
result = client.features.evaluate("user-123", "serviceA-featureX")
if result.error is not None:
print(f"Evaluation error: {result.error.message}")
else:
print(f"Feature enabled: {result.eval}")
pricing_token = client.features.generate_user_pricing_token("user-123")
print(f"Pricing token: {pricing_token}")
client.close()
Async Client
Entitlement checks sit on the request path: a service asks Space "may this user do this?" before serving a request. Made synchronously from inside an event loop, that call blocks every other request the process is serving for as long as it takes - including the full timeout, when Space is slow or unreachable.
AsyncSpaceClient is the same client over httpx.AsyncClient. Same modules,
same method names, same arguments, same exceptions; the calls are awaited.
from space_client import SpaceClientFactory
client = SpaceClientFactory.connect_async(
"http://localhost:3000",
"your-api-key",
10_000,
)
async with client as space:
result = await space.features.evaluate("user-123", "serviceA-featureX")
print(f"Feature enabled: {result.eval}")
token = await space.features.generate_user_pricing_token("user-123")
print(f"Pricing token: {token}")
Two differences, both consequences of running in a loop:
- The WebSocket is not opened by the constructor, because a constructor
cannot await. Call
await client.connect(), or use the client as an async context manager as above, when you want pricing events. HTTP calls work without it. - Closing is awaited:
await client.close(), or leave theasync with.
Everything else - cache lookups and invalidation, request building, error handling - is shared code rather than a second copy, so the two clients cannot drift apart.
The cache providers remain synchronous. An in-memory lookup is not worth an await; a Redis one is a short local round trip, so if you are caching in Redis and want nothing at all blocking the loop, that is worth knowing.
Configuration
You can connect using either convenience factory arguments or SpaceConnectionOptions.
Option A: simple connection
from space_client import SpaceClientFactory
client = SpaceClientFactory.connect("http://localhost:3000", "your-api-key")
Option B: custom timeout
client = SpaceClientFactory.connect("http://localhost:3000", "your-api-key", 15000)
Option C: full options object
from space_client import SpaceClientFactory
from space_client.types import CacheOptions, SpaceConnectionOptions
options = SpaceConnectionOptions(
url="http://localhost:3000",
api_key="your-api-key",
timeout=15000,
cache=CacheOptions(enabled=True),
)
client = SpaceClientFactory.connect(options)
SpaceClientFactory.connect(...) validation rules:
- URL is required and must start with
http://orhttps://. - API key is required.
- Timeout must be a positive number.
API Overview
SpaceClientFactory
| Method | Description |
|---|---|
connect(options) |
Creates a client from full options and validates required inputs. |
connect(url, api_key) |
Convenience overload with default timeout (5000). |
connect(url, api_key, timeout) |
Convenience overload with custom timeout. |
connect_async(...) |
Same arguments and same validation, returning an AsyncSpaceClient. |
SpaceClient
Main entry point. Exposes modules as public fields:
contractsfeaturescache
Core methods:
| Method | Returns | Details |
|---|---|---|
is_connected_to_space() |
bool |
HTTP health check against /healthcheck. |
on(event, callback) |
None |
Registers event callback for supported event names. |
remove_listener(event) |
None |
Removes one callback by event name. |
remove_all_listeners() |
None |
Removes all event callbacks. |
connect() |
None |
Connects/reconnects WebSocket namespace if disconnected. |
disconnect() |
None |
Disconnects WebSocket namespace. |
close() |
None |
Closes sockets, cache provider, and HTTP resources. |
Java-style aliases are also available (isConnectedToSpace, removeListener, removeAllListeners, etc.).
AsyncSpaceClient
The same modules and the same methods, awaited. is_connected_to_space(),
connect(), disconnect() and close() are coroutines; on,
remove_listener and remove_all_listeners are not, since they only touch a
local registry. Supports async with.
ContractModule
| Method | Returns |
|---|---|
get_contract(user_id) |
`Contract |
add_contract(contract_to_create) |
`Contract |
update_contract_subscription(user_id, new_subscription) |
`Contract |
update_contract_subscription_by_group_id(group_id, new_subscription) |
`list[Contract] |
update_contract_usage_levels(user_id, service_name, usage_levels_novations) |
`Contract |
remove_contract(user_id) |
None |
Java-style aliases are also available (getContract, addContract, etc.).
FeatureModule
| Method | Returns |
|---|---|
evaluate(user_id, feature_id, expected_consumption=None, details=False, server=False) |
FeatureEvaluationResult |
revert_evaluation(user_id, feature_id, revert_to_latest=True) |
bool |
generate_user_pricing_token(user_id) |
`str |
Java-style aliases are also available (revertEvaluation, generateUserPricingToken).
Data Models
Main model classes are exported from space_client.types:
SpaceConnectionOptionsCacheOptions,CacheType,ExternalCacheConfig,RedisConfigContract,ContractToCreate,SubscriptionFeatureEvaluationResult,EvaluationErrorBillingPeriod,BillingPeriodToCreate,ContractHistoryEntry,UsageLevel,UserContactSpaceEvent
Caching
Built-in cache is enabled with:
from space_client.types import CacheOptions, SpaceConnectionOptions
options = SpaceConnectionOptions(
url="http://localhost:3000",
api_key="your-api-key",
cache=CacheOptions(enabled=True),
)
Redis cache example:
from space_client.types import (
CacheOptions,
CacheType,
ExternalCacheConfig,
RedisConfig,
SpaceConnectionOptions,
)
options = SpaceConnectionOptions(
url="http://localhost:3000",
api_key="your-api-key",
cache=CacheOptions(
enabled=True,
type=CacheType.REDIS,
external=ExternalCacheConfig(
redis=RedisConfig(host="localhost", port=6379),
),
ttl=300,
),
)
WebSocket Events
Supported event names:
synchronizedpricing_createdpricing_archivedpricing_activedservice_disablederror
Example:
def on_pricing_created(details):
print("Pricing changed:", details)
client.on("pricing_created", on_pricing_created)
client.connect()
Error Handling
- Factory validation raises
ValueErrorfor invalid input. - A request Space refused raises
SpaceApiError, carrying the status code, the method and path, and whatever body came back. - A request that never arrived raises
SpaceConnectionError. FeatureModule.evaluate(...)returns an object containingerrorwhen Space answers successfully with something that is not a usable evaluation.
Both clients raise the same exceptions.
Testing
Run tests locally:
pip install -e .[dev]
pytest
CI executes tests on every pull request for Python 3.10, 3.11, and 3.12.
Contributing
- Create a branch from
main. - Add or update tests for every behavior change.
- Open a pull request.
License
MIT License.
Metadata
Release files for space-python-client 1.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| space_python_client-1.0.0.tar.gz | 48.5 kB | With provenance | Details for space_python_client-1.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| space_python_client-1.0.0-py3-none-any.whl | Python 3 | none | any | Details for space_python_client-1.0.0-py3-none-any.whl |
Total release size: 80.6 kB
Release files / space_python_client-1.0.0.tar.gz
| Download URL | space_python_client-1.0.0.tar.gz |
|---|---|
| Size | 48.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
14ecfd496c55a74e0b2af370da70e4fcf42478b8f71af3b8cc4565ccffce6dee
|
|
BLAKE2b-256 checksum How to use checksums |
66d90e35110da068b447fa9178b6aeb5fa984cc6322358ff072d7d5236d28e1c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 31, 2026.
Transparency logRelease files / space_python_client-1.0.0-py3-none-any.whl
| Download URL | space_python_client-1.0.0-py3-none-any.whl |
|---|---|
| Size | 32.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
9f07559050965c16382cf14050beef29d249fde49634c999b8fed00435876aae
|
|
BLAKE2b-256 checksum How to use checksums |
94c360b2ddcdcb5983f56f42fcd874a505aaeab9a752f3b72faed52ad895efc5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 31, 2026.
Transparency logSecurity for space-python-client 1.0.0
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.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for space_python_client-1.0.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 31, 2026.
Transparency logA 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.