Skip to content
Skills Library
Programming · Building & coding

polar-python-sdk

/polar-python-sdk

Integrate Polar billing in server-side Python applications using the versioned Polar and PolarAsync clients. Use when implementing Polar customers and external IDs, checkout or customer portal sessions, customer-state entitlement checks, webhook validation and processing, API error handling, usage-event ingestion and metered billing, or migrating an application from the old Polar Python SDK.

Repository
polar ↗
Licence
Apache-2.0
Last repository change
27.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
5
Scripts
0
HTML comments
0
URLs in SKILL.md
3
Deprecation

No signals detected. Repository changed on 27.10.2026, without references to retired models or APIs.

Licence

Apache-2.0, otwarta: można używać i zmieniać, z zachowaniem licencji i informacji o zmianach.

What it does and when to use it

Integrate Polar billing in server-side Python applications using the versioned Polar and PolarAsync clients. Use when implementing Polar customers and external IDs, checkout or customer portal sessions, customer-state entitlement checks, webhook validation and processing, API error handling, usage-event ingestion and metered billing, or migrating an application from the old Polar Python SDK.

Original author description

Integrate Polar billing in server-side Python applications using the versioned Polar and PolarAsync clients. Use when implementing Polar customers and external IDs, checkout or customer portal sessions, customer-state entitlement checks, webhook validation and processing, API error handling, usage-event ingestion and metered billing, or migrating an application from the old Polar Python SDK.

How it works

  1. Inspect the application first
  2. Migrate from the old SDK
  3. Configure and reuse the client
  4. Follow generated argument and output conventions
  5. Correlate customers with stable external IDs
  6. Create checkout and customer portal sessions
  7. Reconcile feature access from customer state
  8. Ingest metered usage events
  9. Handle API failures intentionally
Original SKILL.md headings · 149 lines, 829 words
SKILL.md preview
---
name: polar-python-sdk
description: Integrate Polar billing in server-side Python applications using the versioned Polar and PolarAsync clients. Use when implementing Polar customers and external IDs, checkout or customer portal sessions, customer-state entitlement checks, webhook validation and processing, API error handling, usage-event ingestion and metered billing, or migrating an application from the old Polar Python SDK.
---

# Polar Python SDK

Use the generated, versioned Polar SDK without inventing methods or parameters.

## Inspect the application first

1. Identify the installed `polar-sdk` version and preserve the API version already selected by the application.
2. Inspect generated service signatures, input `TypedDict` definitions, output dataclasses, and endpoint-specific errors before writing calls.
3. Use `Polar` in synchronous code and `PolarAsync` in asynchronous code. Do not mix blocking SDK calls into an async request path.
4. Identify whether the access token is scoped to an organization. When the selected token does not imply one, create the client with `Polar(..., organization_id=...)` or pass `organization_id`, and confirm the required endpoint scopes.
5. Keep client, webhook, and environment configuration on the server.

## Migrate from the old SDK

Read [Migration from the `<1.0.0` SDK](references/migration-from-v0.md) before changing an application that imports `polar_sdk`, calls `_async` operation variants, or paginates with `.next()`. Do not mix old and new client, model, pagination, error, or webhook conventions.

## Configure and reuse the client

Keep production and sandbox access tokens separate. Never expose an organization access token in browser, mobile, or other public client code. Pass `environment="sandbox"` while testing; omit it or pass `environment="production"` in production.

```python
import os

from polar.v2026_10 import Polar

with Polar(
    os.environ["POLAR_ACCESS_TOKEN"],
    environment="sandbox",
) as polar:
    customer_state = polar.customers.get_state_external("usr_123")
```

For a long-running service, create one client during application startup, reuse its connection pool, and close it during application shutdown. Do not create a new client for every incoming request.

Use the async client with an application-lifetime async context in async services:

```python
import os

from polar.v2026_10 import PolarAsync


async def load_customer_state() -> None:
    async with PolarAsync(os.environ["POLAR_ACCESS_TOKEN"]) as polar:
        customer_state = await polar.customers.get_state_external("usr_123")
        print(customer_state)
```

## Follow generated argument and output conventions

- Pass path parameters positionally.
- Pass query and request-body parameters as keyword arguments.
- Treat request payload definitions as generated `TypedDict` schemas.
- Treat JSON object responses as generated, slotted dataclass instances or unions.
- Expect UUID and date-time OpenAPI fields to remain strings in this SDK version.
- Use `iter_*` for paginated endpoints. Use `for` with `Polar` and `async for` with `PolarAsync`; each additional page performs another API request.

## Correlate customers with stable external IDs

Use the application's immutable user or organization identifier as the Polar customer `external_id`. It is unique within a Polar organization. It may be assigned later when initially unset, but it cannot be changed or removed once set.

```python
customer = polar.customers.create(
    external_id="usr_123",
    email="user@example.com",
)
customer_state = polar.customers.get_state_external("usr_123")
```

Handle concurrent creation safely. A preflight lookup followed by creation is not atomic; if creation reports an existing email or external ID, fetch and reconcile the existing customer rather than creating a second mapping.

## Create checkout and customer portal sessions

Create checkout sessions on the server and send only the returned URL to the browser. Prefer `external_customer_id` so a completed checkout is reconciled with the application's customer.

```python
checkout = polar.checkouts.create(
    products=[os.environ["POLAR_PRODUCT_ID"]],
    external_customer_id="usr_123",
    success_url="https://example.com/billing/success?checkout_id={CHECKOUT_ID}",
    return_url="https://example.com/settings/billing",
)
redirect_to(checkout.url)
```

Do not treat the success redirect as proof of payment or entitlement. Confirm access through customer state or a verified webhook.

Create short-lived customer portal sessions only for an authenticated customer:

```python
session = polar.customer_sessions.create(
    external_customer_id="usr_123",
    return_url="https://example.com/settings/billing",
)
redirect_to(session.customer_portal_url)
```

Validate return URLs and never let an untrusted caller choose another customer's external ID.

## Reconcile feature access from customer state

Prefer a `feature_flag` benefit attached to the relevant products over inferring access from subscription statuses. Reconcile both access grants and access revocations.

```python
from polar.v2026_10.outputs import CustomerState


def has_feature_access(customer_state: CustomerState, benefit_id: str) -> bool:
    return any(
        grant.benefit_id == benefit_id for grant in customer_state.granted_benefits
    )


customer_state = polar.customers.get_state_external("usr_123")
set_feature_access(
    customer_external_id="usr_123",
    enabled=has_feature_access(
        customer_state,
        os.environ["POLAR_BENEFIT_ID"],
    ),
)
```

Make `set_feature_access` an idempotent application write. A missing benefit must disable access, not merely skip a grant operation.

For webhook-driven synchronization, use benefit-grant events for an incremental local grant ledger or `customer.state_changed` for complete snapshot reconciliation. Read [Webhook processing](references/webhooks.md) before implementing or modifying a receiver.

## Ingest metered usage events

Read [Usage-event ingestion](references/usage-events.md) before implementing metered billing. In particular:

- Match the event name and metadata to the configured meter.
- Associate the event with exactly one `customer_id` or `external_customer_id`.
- Assign every logical event a stable, unique `external_id`.
- Reuse the same `external_id` when retrying so Polar can deduplicate the event.
- Inspect both `inserted` and `duplicates` in the ingestion result.
- Enforce usage limits in the application; ingestion does not reject an action because a customer has exhausted a balance.

## Handle API failures intentionally

Handle generated endpoint-specific errors before broad SDK errors. Classify common base errors as follows:

- `PolarNetworkError`: retry only when the operation is safe or carries a stable deduplication identifier.
- `PolarRateLimitError`: apply bounded backoff and honor `retry_after` when present.
- `PolarServerError`: retry selected 5xx failures with bounded exponential backoff and jitter.
- `PolarClientError`: do not blindly retry authentication, authorization, validation, or not-found failures.

Never create a new usage-event `external_id` during a retry. For other mutations, use an endpoint-supported idempotency mechanism or application-level reconciliation before retrying.
Files in this package (5)
  • SKILL.md 7 KB
  • agents/openai.yaml 1 KB
  • references/migration-from-v0.md 6 KB
  • references/usage-events.md 2 KB
  • references/webhooks.md 4 KB

Versions

RepositoryScoreLicence
This page · polarsource/polar100Apache-2.0
polarsource/polar100Apache-2.0

Database snapshot: 13.11.2026 · package version 467eb7f8d3d3 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100polar-typescript-sdk
    Integrate Polar billing in server-side TypeScript applications using the versioned createPolar and createPolarCore clients. Use when implementing Polar customers and external IDs, checkout or customer portal sessions, customer-state entitlement checks, webhook validation and…
  • 100polar-typescript-sdk
    Integrate Polar billing in server-side TypeScript applications using the versioned createPolar and createPolarCore clients. Use when implementing Polar customers and external IDs, checkout or customer portal sessions, customer-state entitlement checks, webhook validation and…
  • 100polar-integration
    Add Polar billing to a TypeScript/JavaScript app using the @polar-sh/sdk package. Use this skill whenever the user wants to add a Checkout endpoint, a Customer Portal endpoint, or a Webhooks endpoint for Polar to any framework — Next.js, Express, Hono, Astro, SvelteKit, Remix,…
  • 95polar-billing
    This skill should be used when working on Polar billing system, Stripe integration, subscription lifecycle, checkout flows, or benefit provisioning.
  • 100polar-integration
    Add Polar billing to a TypeScript/JavaScript app using the @polar-sh/sdk package. Use this skill whenever the user wants to add a Checkout endpoint, a Customer Portal endpoint, or a Webhooks endpoint for Polar to any framework — Next.js, Express, Hono, Astro, SvelteKit, Remix,…
  • 100polar-testing
    Guide for testing Polar payment integrations using the sandbox environment. Use this skill when: (1) Setting up the Polar sandbox for development; (2) Testing checkout flows without real payments; (3) Using Stripe test cards with Polar; (4) Writing integration tests for payment…

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.