Polar Python SDK
The official Python client for the Polar API.
Installation
The SDK requires Python 3.11 or later.
To install it with uv:
uv add polar-sdk
or, with pip:
pip install polar-sdk
Quick Start
Create an organization access token and use the client for the current API version:
from polar.v2026_10 import Polar
polar = Polar("polar_oat_xxx")
customer_state = polar.customers.get_state_external("customer_external_id")
print(customer_state)
Async Client
Use PolarAsync in asynchronous applications:
import asyncio
from polar.v2026_10 import PolarAsync
async def main() -> None:
polar = PolarAsync("polar_oat_xxx")
customer_state = await polar.customers.get_state_external("customer_external_id")
print(customer_state)
asyncio.run(main())
Context Managers
Both clients support context managers to close their HTTP connections automatically when the block exits.
For synchronous applications, use Polar with with:
from polar.v2026_10 import Polar
with Polar("polar_oat_xxx") as polar:
customer_state = polar.customers.get_state_external("customer_external_id")
print(customer_state)
For asynchronous applications, use PolarAsync with async with:
import asyncio
from polar.v2026_10 import PolarAsync
async def main() -> None:
async with PolarAsync("polar_oat_xxx") as polar:
customer_state = await polar.customers.get_state_external(
"customer_external_id"
)
print(customer_state)
asyncio.run(main())
The client uses the production environment by default. To use the sandbox, pass
environment="sandbox" when creating the client. Sandbox and production access tokens are
separate.
Keep organization access tokens on the server and never expose them in browser or client-side code.
Request Timeouts
Set the default timeout for all requests when creating the client. Timeout values are expressed in seconds:
polar = Polar("polar_oat_xxx", timeout=30)
Override the timeout for an individual request with request_timeout:
customer_state = polar.customers.get_state_external(
"customer_external_id",
request_timeout=60,
)
Override the access token for an individual request with request_access_token:
customer_state = polar.customers.get_state_external(
"customer_external_id",
request_access_token="polar_at_u_override",
)
Pass an httpx2.Timeout or httpx.Timeout instance to configure connect, read, write, and pool timeouts separately.
If your application uses httpx, declare it as a direct dependency.
Organizations
OAuth access tokens and personal access tokens can reach every organization the user belongs to.
Pass organization_id to get a client that acts on a single organization. It sends the
Polar-Organization header, so the API only returns and changes that organization's data:
acme = Polar("polar_at_u_xxx", organization_id="acme_organization_id")
customers = acme.customers.list()
Organization access tokens already act on their own organization and don't need it.
Deserializing Data
Use deserialize to convert arbitrary data into a generated SDK model or union type:
from polar import deserialize
from polar.v2026_10.outputs import Customer
customer = deserialize(data, Customer)
Metering
The metering helper adds buffering, batching, and optional local reduction to the Polar Event Ingestion API.
Basic usage
from polar.v2026_10 import PolarAsync
async def record_usage() -> None:
async with PolarAsync("polar_oat_xxx") as polar:
async with polar.metering() as metering:
await metering.track(
name="api_request",
external_customer_id="customer_123",
metadata={"tokens": 42},
)
An event without a timestamp is dated when you call track(), not when its batch reaches Polar.
Actor context
It's common to have several events for the same customer in the same session. You can create an actor context, so you don't have to pass the customer identifier for each event:
async with polar.metering() as metering:
actor = await metering.actor(external_customer_id="customer_123")
await actor.track(name="api_request", metadata={"tokens": 42})
await actor.track(name="api_request", metadata={"tokens": 17})
Read meters
The metering helper can read meters. Under the hood, it can leverage Outpost to have low-latency reads.
meter = await metering.meter("meter_uuid", external_customer_id="customer_123")
if meter is not None:
print(meter.consumed_units, meter.credited_units, meter.balance)
With an actor context:
actor = await metering.actor(external_customer_id="customer_123")
meter = await actor.meter("meter_uuid")
if meter is not None:
print(meter.consumed_units, meter.credited_units, meter.balance)
Local reduction with Outpost
Outpost is our local reduction engine. It can reduce events locally and share a state across all your clients via Redis. Pass outpost=True to polar.metering() to enable it; it then uses the Redis at the REDIS_URL environment variable.
In high throughput scenarios, Outpost can return you accurate meter reads only milliseconds after the event is ingested.
Outpost needs an external_id on every event; track() rejects an event without one.
A first read of a customer waits up to snapshot_timeout for Polar's snapshot. If it does not arrive in time, the read raises NotReadyError from polar.outpost; the next read asks again.
An event counts locally until Polar confirms it stored it, or refuses it, so a meter read never loses an event Polar is still ingesting.
Outpost delivers the events itself, instead of the buffer: it queues them in Redis and sends them to Polar in batches of up to 1,000 events, shared by every client, on flush() and every second on a long-running server. Pass buffered or outpost, not both.
Pass a dictionary instead of True to configure it.
Delivery
The metering helper queues events in memory and sends them in batches of up to batch_size
events, or every batch_interval seconds. track() never waits for the HTTP request.
On a long-running server, keep one metering context open for the application's lifetime
and let background batching deliver events. Share it between requests on the same event loop.
Leaving the context drains the queue within shutdown_timeout (30 seconds by default) and
raises if any earlier, unacknowledged events could not be confirmed.
In serverless environments such as Vercel or AWS Lambda, await flush(timeout=30) before
returning from each request, so the function does not freeze with events in the queue. It
waits for events queued before the call without closing the shared helper. A newer flush
releases older ones whose deadline is no later than its own and waits for their events too,
so concurrent handlers do not each wait for a round trip to Polar. Concurrent handlers share
HTTP batches.
async def handle_request() -> dict[str, bool]:
await metering.track(name="api_request", external_customer_id="customer_123")
await metering.flush(timeout=30)
return {"ok": True}
For a handler that owns its own helper, context exit drains automatically:
async def handle_request() -> dict[str, bool]:
async with polar.metering(buffered={"shutdown_timeout": 30}) as metering:
await metering.track(name="api_request", external_customer_id="customer_123")
return {"ok": True}
A flush() confirms delivery unless a newer flush released it. Failed delivery raises
MeteringDeliveryError, importable from polar.metering. Its events contains the unconfirmed events; each item in
failures includes events, a reason, and the original cause. Drops are still logged
and passed to on_dropped. A completed flush acknowledges the reported failures, so a later
flush reports only subsequent outcomes. The newest overlapping flush reports the failures of
the ones it released.
Periodically flush long-running helpers to observe failures and release their retained records.
If the wait expires, flush() raises MeteringTimeoutError. Timeout and caller cancellation
do not stop background delivery or other callers, and leave failures observable by a later
flush or context exit. The flush timeout bounds the caller's wait; shutdown_timeout bounds
context cleanup. Both are independent of the HTTP client's request timeout. Shutdown may
interrupt delivery callbacks when its deadline expires. If both the context body and delivery
fail, exit raises an exception group preserving both errors.
When Polar answers 429 Too Many Requests, the helper waits for Retry-After, then sends
full batches. A flush waits for this delivery only up to its timeout. The rate limit counts
requests, not events, so batching keeps request volume down.
The buffer is in memory: forced process termination can still lose events. Choose deadlines that fit within the function's execution limit; use durable storage when delivery must survive termination. A timeout means delivery is unconfirmed, so blindly retrying may duplicate events.
Options
Buffered
The metering helper buffers events in memory and sends them in batches to Polar. It retries network errors and server errors with exponential backoff and jitter. On a rate limit it waits out Retry-After, for up to five minutes per batch. Other Polar API errors drop the batch without retrying.
| Option | Default | Meaning |
|---|---|---|
batch_size |
100 |
Maximum events per HTTP request. |
batch_interval |
1.0 |
Seconds to collect a batch, starting with its first event. |
shutdown_timeout |
30.0 |
Seconds allowed to drain on context exit. |
max_attempts |
3 |
Total attempts per batch, including the first. |
on_delivered |
None |
Async callback receiving the events Polar accepted. |
on_dropped |
None |
Async callback receiving the dropped events and reason. |
Outpost
| Option | Default | Meaning |
|---|---|---|
redis_url |
REDIS_URL environment variable |
Redis instance used by Outpost. |
telemetry |
True |
Send Outpost metrics and traces to Polar. |
snapshot_timeout |
5 |
Seconds a cold read waits for its initial snapshot. |
on_delivered |
None |
Async callback receiving the events Polar accepted. |
on_dropped |
None |
Async callback receiving the refused events and reason. |
Telemetry can also be disabled with the POLAR_OUTPOST_TELEMETRY=0 environment variable.
Webhooks
Use validate_event to verify that a webhook was sent by Polar and parse it into a typed payload
for the selected API version. Pass the raw request body, the request headers, and your webhook
signing secret:
import os
from fastapi import FastAPI, HTTPException, Request
from polar.v2026_10.webhooks import (
PolarWebhookError,
PolarWebhookVerificationError,
validate_event,
)
app = FastAPI()
webhook_secret = os.environ["POLAR_WEBHOOK_SECRET"]
@app.post("/webhooks/polar")
async def polar_webhook(request: Request) -> dict[str, bool]:
try:
event = validate_event(
await request.body(),
dict(request.headers),
webhook_secret,
)
except PolarWebhookVerificationError as exc:
raise HTTPException(
status_code=403, detail="Invalid webhook signature"
) from exc
except PolarWebhookError as exc:
raise HTTPException(status_code=400, detail="Invalid webhook payload") from exc
if event.type == "order.created":
print(event.data.id)
return {"received": True}
The signature is checked before the body is parsed. Verification accepts Polar's
original HMAC key (UTF-8 bytes of the full secret, including whsec_) and the
Standard Webhooks key (base64-decode of the remainder after whsec_).
validate_event raises PolarWebhookVerificationError for invalid signatures and
PolarWebhookUnknownTypeError when the event is not supported by the selected API
version. Both inherit from PolarWebhookError.
Metadata
Release files for polar-sdk 1.3.2
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 |
|---|---|---|---|---|
| polar_sdk-1.3.2.tar.gz | 446.0 kB | Without provenance | Details for polar_sdk-1.3.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| polar_sdk-1.3.2-py3-none-any.whl | Python 3 | none | any | Details for polar_sdk-1.3.2-py3-none-any.whl |
Total release size: 958.8 kB
Release files / polar_sdk-1.3.2.tar.gz
| Download URL | polar_sdk-1.3.2.tar.gz |
|---|---|
| Size | 446.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
be70a3e3ae8480cab933bdf8607a02e1eb08371b2225744412ca04532334961c
|
|
BLAKE2b-256 checksum How to use checksums |
8e56d657d87df1a5f43254315ef3be24031662b01ac97ba6fc221213ca319055
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / polar_sdk-1.3.2-py3-none-any.whl
| Download URL | polar_sdk-1.3.2-py3-none-any.whl |
|---|---|
| Size | 512.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
786379ad5dcca69015830437b7ac12a46ef0bfe1c9e636715351c03739dda517
|
|
BLAKE2b-256 checksum How to use checksums |
b7492802a90bc70d67492ee373b53d8192ec46e07f1d0662817f2a6361b49a6e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for polar-sdk 1.3.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.