Skip to main content

sub2api

sub2api is a Python client for the shared user-facing panel API exposed by Sub2API instances. One client object represents one user's dashboard session. Requests use curl_cffi with Chrome browser impersonation by default.

The library targets operations present on standard Sub2API deployments: account balance, optional payment deposits, payment orders, platform quotas, usage history and statistics, API keys, groups, subscriptions, announcements, and redemption.

Install

pip install sub2api

Python 3.10 or newer is required.

Authenticate with an existing session

The client authenticates with a dashboard access token. If your integration owns the session and its renewal, you can also supply its refresh token.

import os

from sub2api import Sub2API

client = Sub2API(
    "https://sub2api.example.com",
    access_token=os.environ["SUB2API_ACCESS_TOKEN"],
    refresh_token=os.environ.get("SUB2API_REFRESH_TOKEN"),
)

print(client.me().email)
print(client.balance().balance)

Pass either the instance origin or its full /api/v1 URL. By default, the client keeps its tokens in memory and attempts renewal after an authenticated 401 if it has a refresh token. Supplying expires_at as a Unix timestamp also enables proactive renewal within 30 seconds of expiry.

The default browser fingerprint is Chrome. The selected curl_cffi browser profile also supplies the default User-Agent. You can choose another profile, set a custom User-Agent, or configure proxies with your own curl_cffi.requests.Session.

from curl_cffi import requests

session = requests.Session(impersonate="safari")
client = Sub2API("https://sub2api.example.com", session=session)

Use a browser-managed session

If the dashboard owns renewal, pass its access token with externally_managed=True. The client surfaces the original 401. When the dashboard supplies a new token, call set_access_token() on the existing client. You can pass expires_at with either call to retain the dashboard's expiry timestamp.

client = Sub2API(
    "https://sub2api.example.com",
    access_token=dashboard_access_token,
    externally_managed=True,
)
client.set_access_token(updated_dashboard_access_token)

Persist and share a library-managed session

Pass a token_store that implements TokenStore. The client uses the stored SessionTokens when present and can initialize an empty store from the constructor credentials. Keep one store per user session and instance. Each write must persist access_token, refresh_token, expires_at, and token_type together.

  • load() returns the current snapshot, or None for an uninitialized store.
  • save(tokens) atomically replaces the snapshot after a successful login, including 2FA.
  • compare_and_set(expected, tokens) atomically replaces the snapshot only if it matches expected. Return False when another writer has changed it. An empty SessionTokens() snapshot represents a cleared session.

When multiple clients share the session, pass the same refresh_lock to each client along with the shared store. A threading.Lock() works for threads in one process. Workers in separate processes need a lock that coordinates across those processes and supports with. Clients reload the stored pair under that lock and save a rotation before releasing it or retrying the original request.

If the rotation write raises, the client surfaces the store exception and keeps the new pair in client.tokens. Call client.save_tokens() to retry the conditional write without another refresh request. A newer login in the store takes precedence over a pending rotation.

Rate limits, transport errors, and server errors during renewal leave credentials intact. HTTP errors expose retry_after in seconds when the server supplies a valid Retry-After header. After a transport failure the client checks the store for a replacement pair, and surfaces TransportError if it finds none. SessionExpiredError, SessionRevokedError, and SessionBindingError are subclasses of AuthenticationError that carry the server's reason or code.

Log in with email and password

from sub2api import Sub2API

with Sub2API("https://sub2api.example.com") as client:
    user = client.login("person@example.com", "password")
    print(user.username)
    print(client.is_authenticated)

An instance with CAPTCHA enabled requires the corresponding proof:

client.login(
    "person@example.com",
    "password",
    turnstile_token="captcha-proof",
)

For a TOTP-enabled account, login() raises TwoFactorRequired and retains the temporary challenge in memory:

from sub2api import Sub2API, TwoFactorRequired

client = Sub2API("https://sub2api.example.com")

try:
    client.login("person@example.com", "password")
except TwoFactorRequired:
    client.complete_2fa("123456")

Common operations

Resources are callable for their common list operation and also expose explicit methods.

balance = client.balance()
quotas = client.account.platform_quotas()

groups = client.groups()
group_rates = client.groups.rates()

first_page = client.keys(page_size=50, status="active")
for api_key in first_page:
    print(api_key.id, api_key.name, api_key.group.name)

all_keys = client.keys.all()
resolved = client.keys.with_group_multipliers()
for item in resolved:
    print(
        item.api_key.key,
        item.group_id,
        item.base_multiplier,
        item.custom_multiplier,
        item.effective_multiplier,
    )

multiplier_by_key = client.keys.multiplier_map(key_by="key")
multiplier_by_id = client.keys.multiplier_map(key_by="id")

created = client.keys.create("automation", group_id=groups[0].id)
client.keys.update(created.id, name="nightly automation")
client.keys.set_status(created.id, active=False)
client.keys.delete(created.id)

all() follows pagination until every key has been fetched. with_group_multipliers() joins each key to its group and reports the base, user-specific, and effective rate; the user-specific rate from /groups/rates takes precedence. multiplier_map() returns the effective rate keyed by the API key value, key ID, or name. Name collisions raise an error instead of silently overwriting an entry.

API key values are available through api_key.key, but object representations redact fields that commonly contain credentials.

Usage history

history and usage refer to the same resource.

from datetime import date, timedelta

end = date.today()
start = end - timedelta(days=7)

page = client.history(
    start_date=start,
    end_date=end,
    page_size=100,
    sort_by="created_at",
    sort_order="desc",
)

for record in page:
    print(record.created_at, record.model, record.actual_cost)

for record in client.history.iter(page_size=100):
    process(record)

stats = client.usage.stats(start_date=start, end_date=end)
dashboard = client.usage.dashboard()
trend = client.usage.trend(start_date=start, end_date=end, granularity="day")
models = client.usage.models(start_date=start, end_date=end)
snapshot = client.usage.snapshot(start_date=start, end_date=end)

Other shared resources

active_subscriptions = client.subscriptions(active=True)
announcements = client.announcements()
client.announcements.mark_read(announcements[0].id)

result = client.redeem("REDEMPTION-CODE")
redemption_history = client.redeem.history()

Deposits and payment

Payment is optional and must be enabled and configured by the instance administrator. Inspect the checkout configuration before offering a deposit:

checkout = client.payment.checkout_info()

if checkout.methods:
    order = client.deposit(
        10,
        payment_type="stripe",
        return_url="https://app.example.com/payment/result",
    )
    print(order.order_id, order.pay_url, order.qr_code, order.client_secret)

Available payment methods depend on the instance and can include alipay, wxpay, stripe, and airwallex. The returned order contains the provider-specific checkout data: a hosted payment URL, QR code, Stripe client secret, or WeChat OAuth/JSAPI payload. Creating the order does not credit the balance; the configured provider must confirm payment before the instance completes the deposit.

Use the payment resource to inspect and manage the order:

pending = client.payment.get(order.order_id)
verified = client.payment.verify(order.out_trade_no)
orders = client.payment.list(status="COMPLETED", order_type="balance")
client.payment.cancel(order.order_id)

An instance without payment configuration returns its normal typed API error, including PAYMENT_DISABLED or NO_AVAILABLE_INSTANCE, rather than silently treating a deposit as successful. Public order recovery is also available when a checkout flow has a signed resume token:

public_order = client.payment.resolve_public(order.resume_token)

Fork-specific endpoints

request() provides the same authentication, envelope handling, timezone parameter, refresh behavior, and error mapping for relative endpoints that are not part of the stable resource API.

result = client.request("GET", "some-fork-specific-endpoint")

Absolute URLs and parent-path traversal are rejected so a session token cannot be redirected outside the configured API root.

Errors

HTTP and Sub2API envelope failures use typed exceptions:

from sub2api import AuthenticationError, RateLimitError, Sub2APIError

try:
    client.keys.create("automation")
except RateLimitError as error:
    print(error.retry_after)
except AuthenticationError:
    client.login("person@example.com", "password")
except Sub2APIError as error:
    print(error)

Remote plaintext HTTP is rejected by default because it exposes login credentials and tokens. Localhost HTTP is allowed for development; other HTTP instances require allow_insecure=True.

Metadata

Release files for sub2api 0.3.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sub2api 0.3.1
File Size Uploaded Provenance Actions
sub2api-0.3.1.tar.gz 25.0 kB Without provenance Details for sub2api-0.3.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for sub2api 0.3.1
File Interpreter ABI Platform Actions
sub2api-0.3.1-py3-none-any.whl Python 3 none any Details for sub2api-0.3.1-py3-none-any.whl

Total release size: 46.5 kB

Release files / sub2api-0.3.1.tar.gz

Download URL sub2api-0.3.1.tar.gz
Size 25.0 kB
Tags Source
SHA-256 checksum
How to use checksums
12b16f472dafb9bbd9eaba334ed6fb12991a79996042d4428f4f264ae5d187f2
BLAKE2b-256 checksum
How to use checksums
d59a0333c64c21cbeb37dc69cbd0d8f3721b407d395ca3a98e4ee90631cefa22
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.0

Release files / sub2api-0.3.1-py3-none-any.whl

Download URL sub2api-0.3.1-py3-none-any.whl
Size 21.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
15202b0bfd60b41d58e45fae993a70a3fc0e47400a8f1dccf208824ba885d230
BLAKE2b-256 checksum
How to use checksums
a9521cbf6e8fd1c4032b68ef129fabe664a0a5eaba5c90344925329e911c9db9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.0

Security for sub2api 0.3.1

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page