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
- Add
schematichqto your project’s build file:
-
Issue an API key for the appropriate environment using the Schematic app.
-
Using this secret key, initialize a client in your application:
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:
Context Manager (Recommended)
Use the async client as a context manager for automatic lifecycle management:
Production Usage (Explicit Control)
For production applications that need precise control over initialization timing:
Exception Handling
All errors thrown by the SDK will be subclasses of ApiError.
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.
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.
Async client:
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:
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:
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:
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.
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
Django
FastAPI
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:
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):
You can also disable local caching entirely; bear in mind that, in this case, every flag check will result in a network request:
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):
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:
Offline mode works well with flag defaults:
Timeouts
By default, requests time out after 60 seconds. You can configure this with a timeout option at the client or request level.
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:
Use the max_retries request option to configure this behavior.
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.
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
AsyncSchematicclient. The synchronousSchematicclient does not support either feature — useAsyncSchematic(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:
To use the Redis-backed shared cache (see below), also install 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
AsyncCacheProviderimplementations including a built-in Redis provider.
How to Enable DataStream
Set use_datastream=True on AsyncSchematicConfig:
Configuration Options
All fields live on DataStreamConfig.
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:
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
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:
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