Schematic Python Library

The Schematic Python Library provides convenient access to the Schematic API from applications written in Python.

The library includes type definitions for all request and response fields, and offers both synchronous and asynchronous clients powered by httpx.

Installation and Setup

  1. Add schematichq to your project’s build file:
$pip install schematichq
$# or
$poetry add schematichq
  1. Issue an API key for the appropriate environment using the Schematic app.

  2. Using this secret key, initialize a client in your application:

1from schematic.client import Schematic
2
3client = Schematic("YOUR_API_KEY")

Async Client

The SDK exports an async client for non-blocking API calls with automatic background event processing. The async client features lazy initialization - you can start using it immediately without manual setup.

Simple Usage (Lazy Initialization)

The easiest way to use the async client - just create and use it directly:

1import asyncio
2from schematic.client import AsyncSchematic
3
4async def main():
5 # Create client - no initialize() needed!
6 client = AsyncSchematic("YOUR_API_KEY")
7
8 # Use immediately - auto-initializes on first call
9 is_enabled = await client.check_flag(
10 "new-feature",
11 company={"id": "company-123"},
12 user={"id": "user-456"}
13 )
14
15 if is_enabled:
16 print("New feature is enabled!")
17
18 # Track usage
19 await client.track(
20 event="feature-used",
21 company={"id": "company-123"},
22 user={"id": "user-456"}
23 )
24
25 # Always shutdown when done
26 await client.shutdown()
27
28asyncio.run(main())

Use the async client as a context manager for automatic lifecycle management:

1import asyncio
2from schematic.client import AsyncSchematic
3
4async def main():
5 async with AsyncSchematic("YOUR_API_KEY") as client:
6 # Client auto-initializes and will auto-shutdown
7
8 is_enabled = await client.check_flag(
9 "feature-flag",
10 company={"id": "company-123"}
11 )
12
13 await client.identify(
14 keys={"id": "company-123"},
15 name="Acme Corp"
16 )
17
18 # Automatic cleanup on exit
19
20asyncio.run(main())

Production Usage (Explicit Control)

For production applications that need precise control over initialization timing:

1import asyncio
2from schematic.client import AsyncSchematic
3
4# Web application example
5client = AsyncSchematic("YOUR_API_KEY")
6
7async def startup():
8 """Call during application startup"""
9 await client.initialize() # Start background tasks now
10 print("Schematic client ready")
11
12async def shutdown():
13 """Call during application shutdown"""
14 await client.shutdown() # Stop background tasks and flush events
15 print("Schematic client stopped")
16
17async def handle_request():
18 """Handle individual requests"""
19 # Client is already initialized - this will be fast
20 is_enabled = await client.check_flag(
21 "feature-flag",
22 company={"id": "company-123"}
23 )
24 return {"feature_enabled": is_enabled}

Exception Handling

All errors thrown by the SDK will be subclasses of ApiError.

1try:
2 client.companies.get_company(
3 company_id="company_id",
4 )
5except schematic.core.ApiError as e: # Handle all errors
6 print(e.status_code)
7 print(e.body)

Usage examples

A number of these examples use keys to identify companies and users. Learn more about keys here.

Sending identify events

Create or update users and companies using identify events.

1from schematic import EventBodyIdentifyCompany
2from schematic.client import Schematic
3
4client = Schematic("YOUR_API_KEY")
5
6client.identify(
7 keys={
8 "email": "wcoyote@acme.net",
9 "user_id": "your-user-id",
10 },
11 company=EventBodyIdentifyCompany(
12 keys={"id": "your-company-id"},
13 name="Acme Widgets, Inc.",
14 traits={
15 "city": "Atlanta",
16 },
17 ),
18 name="Wile E. Coyote",
19 traits={
20 "login_count": 24,
21 "is_staff": false,
22 },
23)

This call is non-blocking and there is no response to check.

Sending track events

Track activity in your application using track events; these events can later be used to produce metrics for targeting.

1from schematic.client import Schematic
2
3client = Schematic("YOUR_API_KEY")
4
5client.track(
6 event="some-action",
7 user={"user_id": "your-user-id"},
8 company={"id": "your-company-id"},
9)

Async client:

1import asyncio
2from schematic.client import AsyncSchematic
3
4async def main():
5 async with AsyncSchematic("YOUR_API_KEY") as client:
6 await client.track(
7 event="some-action",
8 user={"user_id": "your-user-id"},
9 company={"id": "your-company-id"},
10 )
11
12asyncio.run(main())

These calls are non-blocking and there is no response to check.

If you want to record large numbers of the same event at once, or perhaps measure usage in terms of a unit like tokens or memory, you can optionally specify a quantity for your event:

1client.track(
2 event="some-action",
3 user={"user_id": "your-user-id"},
4 company={"id": "your-company-id"},
5 quantity=10,
6)

Creating and updating companies

Although it is faster to create companies and users via identify events, if you need to handle a response, you can use the companies API to upsert companies. Because you use your own identifiers to identify companies, rather than a Schematic company ID, creating and updating companies are both done via the same upsert operation:

1from schematic.client import Schematic
2
3client = Schematic("YOUR_API_KEY")
4
5client.companies.upsert_company(
6 keys={"id": "your-company-id"},
7 name="Acme Widgets, Inc.",
8 traits={
9 "city": "Atlanta",
10 "high_score": 25,
11 "is_active": true,
12 },
13)

You can define any number of company keys; these are used to address the company in the future, for example by updating the company’s traits or checking a flag for the company.

You can also define any number of company traits; these can then be used as targeting parameters.

Creating and updating users

Similarly, you can upsert users using the Schematic API, as an alternative to using identify events. Because you use your own identifiers to identify users, rather than a Schematic user ID, creating and updating users are both done via the same upsert operation:

1from schematic.client import Schematic
2
3client = Schematic("YOUR_API_KEY")
4
5client.companies.upsert_user(
6 keys={
7 "email": "wcoyote@acme.net",
8 "user_id": "your-user-id",
9 },
10 name="Wile E. Coyote",
11 traits={
12 "city": "Atlanta",
13 "high_score": 25,
14 "is_active": true,
15 },
16 company={"id": "your-company-id"},
17)

You can define any number of user keys; these are used to address the user in the future, for example by updating the user’s traits or checking a flag for the user.

You can also define any number of user traits; these can then be used as targeting parameters.

Checking flags

When checking a flag, you’ll provide keys for a company and/or keys for a user. You can also provide no keys at all, in which case you’ll get the default value for the flag.

1from schematic.client import Schematic
2
3client = Schematic("YOUR_API_KEY")
4
5client.check_flag(
6 "some-flag-key",
7 company={"id": "your-company-id"},
8 user={"user_id": "your-user-id"},
9)

Webhook Verification

Schematic can send webhooks to notify your application of events. To ensure the security of these webhooks, Schematic signs each request using HMAC-SHA256. The Python SDK provides utility functions to verify these signatures.

Verifying Webhook Signatures

When your application receives a webhook request from Schematic, you should verify its signature to ensure it’s authentic. The SDK provides simple functions to verify webhook signatures. Here’s how to use them in different frameworks:

Flask

1from flask import Flask, request, jsonify
2from schematic.webhook_utils import verify_webhook_signature, WebhookSignatureError
3
4app = Flask(__name__)
5
6@app.route('/webhooks/schematic', methods=['POST'])
7def schematic_webhook():
8 try:
9 # Each webhook has a distinct secret; you can access this via the Schematic app
10 webhook_secret = "your-webhook-secret"
11
12 # Verify the webhook signature
13 verify_webhook_signature(request, webhook_secret)
14
15 # Process the webhook payload
16 data = request.json
17 print(f"Webhook verified: {data}")
18
19 return "", 200
20 except WebhookSignatureError as e:
21 print(f"Webhook verification failed: {str(e)}")
22 return jsonify({"error": str(e)}), 400
23 except Exception as e:
24 print(f"Error processing webhook: {str(e)}")
25 return jsonify({"error": "Internal server error"}), 500
26
27if __name__ == '__main__':
28 app.run(port=3000)

Django

1from django.http import JsonResponse, HttpResponse
2from django.views.decorators.csrf import csrf_exempt
3from schematic.webhook_utils import verify_webhook_signature, WebhookSignatureError
4
5@csrf_exempt
6def schematic_webhook(request):
7 if request.method != 'POST':
8 return HttpResponse(status=405)
9
10 try:
11 # Each webhook has a distinct secret; you can access this via the Schematic app
12 webhook_secret = "your-webhook-secret"
13
14 # Verify the webhook signature
15 verify_webhook_signature(request, webhook_secret)
16
17 # Process the webhook payload
18 data = request.json
19 print(f"Webhook verified: {data}")
20
21 return HttpResponse(status=200)
22 except WebhookSignatureError as e:
23 print(f"Webhook verification failed: {str(e)}")
24 return JsonResponse({"error": str(e)}, status=400)
25 except Exception as e:
26 print(f"Error processing webhook: {str(e)}")
27 return JsonResponse({"error": "Internal server error"}, status=500)

FastAPI

1from fastapi import FastAPI, Request, Response, HTTPException, Depends
2from schematic.webhook_utils import verify_webhook_signature, WebhookSignatureError
3
4app = FastAPI()
5
6async def verify_signature(request: Request):
7 # Each webhook has a distinct secret; you can access this via the Schematic app
8 webhook_secret = "your-webhook-secret"
9
10 try:
11 # Get the raw body
12 body = await request.body()
13
14 # Verify the webhook signature
15 verify_webhook_signature(request, webhook_secret, body)
16 except WebhookSignatureError as e:
17 raise HTTPException(status_code=400, detail=str(e))
18
19@app.post("/webhooks/schematic")
20async def schematic_webhook(request: Request, _: None = Depends(verify_signature)):
21 # Process the webhook payload
22 data = await request.json()
23 print(f"Webhook verified: {data}")
24
25 return Response(status_code=200)

Verifying Signatures Manually

If you need to verify a webhook signature outside of the context of a web request, you can use the verify_signature function:

1from schematic.webhook_utils import verify_signature, WebhookSignatureError
2
3def verify_webhook_manually(body: str, signature: str, timestamp: str, secret: str):
4 try:
5 # Verify the signature
6 verify_signature(body, signature, timestamp, secret)
7 return True
8 except WebhookSignatureError as e:
9 print(f"Webhook verification failed: {str(e)}")
10 return False

Advanced

Flag Check Options

By default, the client will do some local caching for flag checks. If you would like to change this behavior, you can do so using an initialization option to specify the max size of the cache (in terms of number of entries) and the max age of the cache (in milliseconds):

1from schematic.client import LocalCache, Schematic
2
3cache_size = 100
4cache_ttl = 1000 # in milliseconds
5config = SchematicConfig(
6 cache_providers=[LocalCache[bool](cache_size, cache_ttl)],
7)
8client = Schematic("YOUR_API_KEY", config)

You can also disable local caching entirely; bear in mind that, in this case, every flag check will result in a network request:

1from schematic.client import Schematic
2
3config = SchematicConfig(cache_providers=[])
4client = Schematic("YOUR_API_KEY", config)

You may want to specify default flag values for your application, which will be used if there is a service interruption or if the client is running in offline mode (see below):

1from schematic.client import Schematic
2
3config = SchematicConfig(flag_defaults={"some-flag-key": True})
4client = Schematic("YOUR_API_KEY", config)

Offline Mode

In development or testing environments, you may want to avoid making network requests to the Schematic API. You can run Schematic in offline mode by specifying the offline option; in this case, it does not matter what API key you specify:

1from schematic.client import Schematic
2
3config = SchematicConfig(offline=True)
4client = Schematic("", config)

Offline mode works well with flag defaults:

1from schematic.client import Schematic
2
3config = SchematicConfig(
4 flag_defaults={"some-flag-key": True},
5 offline=True,
6)
7client = Schematic("", config)
8client.check_flag("some-flag-key") # Returns True

Timeouts

By default, requests time out after 60 seconds. You can configure this with a timeout option at the client or request level.

1from schematic.client import Schematic
2
3client = Schematic(
4 # All timeouts are 20 seconds
5 timeout=20.0,
6)
7
8# Override timeout for a specific method
9client.companies.get_company(..., {
10 timeout_in_seconds=20.0
11})

Retries

The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long as the request is deemed retriable and the number of retry attempts has not grown larger than the configured retry limit (default: 2).

A request is deemed retriable when any of the following HTTP status codes is returned:

  • 408 (Timeout)
  • 429 (Too Many Requests)
  • 5XX (Internal Server Errors)

Use the max_retries request option to configure this behavior.

1# Override timeout for a specific method
2client.companies.get_company(..., {
3 max_retries=1 # Only retry once on failure
4})

Custom HTTP client

You can override the httpx client to customize it for your use-case. Some common use-cases include support for proxies and transports.

1import httpx
2
3from schematic.client import Schematic
4
5client = Schematic(
6 http_client=httpx.Client(
7 proxies="http://my.test.proxy.example.com",
8 transport=httpx.HTTPTransport(local_address="0.0.0.0"),
9 ),
10)

DataStream

DataStream enables local flag evaluation by maintaining a WebSocket connection to Schematic and caching flag rules, company, and user data locally (or in a shared cache such as Redis). Flag checks are evaluated locally via a WASM rules engine, eliminating per-check network requests.

Async-only: DataStream and Replicator Mode are only available on the AsyncSchematic client. The synchronous Schematic client does not support either feature — use AsyncSchematic (shown in all examples below) if you need them.

Installation

DataStream requires additional dependencies for WebSocket connections and local flag evaluation. Install them with the datastream extra:

$pip install 'schematichq[datastream]'
$# or
$poetry add schematichq -E datastream

To use the Redis-backed shared cache (see below), also install redis:

$pip install 'schematichq[datastream]' redis

Key Features

  • Real-Time Updates: Automatically updates cached data when changes occur on the backend.
  • Local Flag Evaluation: Flag checks are evaluated locally via WASM, eliminating per-check network requests.
  • Configurable Caching: Supports in-memory caching (default) and custom AsyncCacheProvider implementations including a built-in Redis provider.

How to Enable DataStream

Set use_datastream=True on AsyncSchematicConfig:

1import asyncio
2from schematic.client import AsyncSchematic, AsyncSchematicConfig, DataStreamConfig
3
4async def main():
5 config = AsyncSchematicConfig(
6 use_datastream=True,
7 datastream=DataStreamConfig(
8 cache_ttl=300_000, # 5 minutes, in ms
9 ),
10 )
11
12 async with AsyncSchematic("YOUR_API_KEY", config) as client:
13 is_enabled = await client.check_flag(
14 "some-flag-key",
15 company={"id": "your-company-id"},
16 user={"id": "your-user-id"},
17 )
18
19asyncio.run(main())

Configuration Options

All fields live on DataStreamConfig.

OptionTypeDefaultDescription
cache_ttlOptional[int]24 hoursCache TTL in milliseconds. None means no expiration.
company_cacheAsyncCacheProviderin-memoryCache for full company records.
company_lookup_cacheAsyncCacheProviderin-memoryCache mapping company keys → company IDs.
user_cacheAsyncCacheProviderin-memoryCache for full user records.
user_lookup_cacheAsyncCacheProviderin-memoryCache mapping user keys → user IDs.
flag_cacheAsyncCacheProviderin-memoryCache for flag rules.
replicator_modeboolFalseEnable Replicator Mode (see below).
replicator_health_urlOptional[str]http://localhost:8090/readyReplicator health check URL.
replicator_health_checkOptional[int]30000Health check interval in milliseconds.

Using Redis as a Shared Cache

The SDK ships with a RedisCache provider built on redis.asyncio. Pass a Redis client into the cache slots on DataStreamConfig to share state across multiple processes:

1import asyncio
2import redis.asyncio as aioredis
3from schematic.cache import RedisCache
4from schematic.client import AsyncSchematic, AsyncSchematicConfig, DataStreamConfig
5
6async def main():
7 redis_client = aioredis.from_url("redis://localhost:6379")
8 cache_ttl_ms = 60 * 60 * 1000 # 1 hour
9
10 config = AsyncSchematicConfig(
11 use_datastream=True,
12 datastream=DataStreamConfig(
13 cache_ttl=cache_ttl_ms,
14 company_cache=RedisCache(redis_client, default_ttl_ms=cache_ttl_ms),
15 company_lookup_cache=RedisCache(redis_client, default_ttl_ms=cache_ttl_ms),
16 user_cache=RedisCache(redis_client, default_ttl_ms=cache_ttl_ms),
17 user_lookup_cache=RedisCache(redis_client, default_ttl_ms=cache_ttl_ms),
18 flag_cache=RedisCache(redis_client, default_ttl_ms=cache_ttl_ms),
19 ),
20 )
21
22 async with AsyncSchematic("YOUR_API_KEY", config) as client:
23 await client.check_flag("some-flag-key", company={"id": "your-company-id"})
24
25asyncio.run(main())

RedisCache accepts a prefix argument (default "schematic") if you need to namespace keys — this must match the prefix used by any other SDKs or the replicator writing to the same Redis instance.

Replicator Mode

When running the schematic-datastream-replicator service, configure the client to operate in Replicator Mode. The replicator holds the single WebSocket connection to Schematic and populates a shared cache; SDK instances read from that cache and evaluate flags locally without opening their own WebSocket connections.

Replicator Mode requires a shared cache (e.g. Redis) so the SDK can read data written by the external replicator process. Configure the cache slots on DataStreamConfig exactly as in the Redis example above.

How to Enable Replicator Mode

1import asyncio
2import redis.asyncio as aioredis
3from schematic.cache import RedisCache
4from schematic.client import AsyncSchematic, AsyncSchematicConfig, DataStreamConfig
5
6async def main():
7 redis_client = aioredis.from_url("redis://localhost:6379")
8
9 config = AsyncSchematicConfig(
10 use_datastream=True,
11 datastream=DataStreamConfig(
12 replicator_mode=True,
13 cache_ttl=None, # Match the replicator's unlimited default
14 company_cache=RedisCache(redis_client),
15 company_lookup_cache=RedisCache(redis_client),
16 user_cache=RedisCache(redis_client),
17 user_lookup_cache=RedisCache(redis_client),
18 flag_cache=RedisCache(redis_client),
19 ),
20 )
21
22 async with AsyncSchematic("YOUR_API_KEY", config) as client:
23 is_enabled = await client.check_flag(
24 "some-flag-key",
25 company={"id": "your-company-id"},
26 )
27
28asyncio.run(main())

Cache TTL Configuration

Set the SDK’s cache_ttl to match the replicator’s cache TTL. The replicator defaults to an unlimited cache TTL. If the SDK uses a shorter TTL (the default is 24 hours), locally updated cache entries (e.g. after track events) will be written back with the shorter TTL and eventually evicted from the shared cache, even though the replicator originally set them with no expiration.

If you have configured a custom cache TTL on the replicator, use the same value here.

Advanced Configuration

The client automatically configures sensible defaults for Replicator Mode, but you can customize the health check endpoint and interval:

1config = AsyncSchematicConfig(
2 use_datastream=True,
3 datastream=DataStreamConfig(
4 replicator_mode=True,
5 cache_ttl=None,
6 replicator_health_url="http://my-replicator:8090/ready",
7 replicator_health_check=60_000, # 60 seconds, in ms
8 # ... shared cache providers
9 ),
10)

Default Configuration

  • Replicator Health URL: http://localhost:8090/ready
  • Health Check Interval: 30 seconds
  • Cache TTL: 24 hours (SDK default; should be set to match the replicator’s TTL, which defaults to unlimited)

When running in Replicator Mode, the client will:

  • Skip establishing WebSocket connections
  • Periodically check if the replicator service is ready
  • Use cached data populated by the external replicator service
  • Fall back to direct API calls if the replicator is not available