Skip to main content

DiOTP Python SDK

PyPI version Python versions CI License: MIT

The official Python client for the DiOTP OTP API. Send a one-time password by SMS (or WhatsApp, once it is switched on for your account) and verify the code your user types.

  • Sync (DiOTP) and async (AsyncDiOTP) clients with the same methods.
  • Typed, immutable results and a typed exception for every documented error code.
  • Automatic retries with exponential backoff, and an Idempotency-Key on every send so a retry never sends a second code.
  • Webhook signature verification.
  • Python 3.9 or later. One dependency: httpx.

Documentation: https://diotp.diorbit.com/docs (SDK page: diotp.diorbit.com/docs/sdks).

Install

pip install diotp

Quickstart

Keep your API key on the server, in the DIOTP_API_KEY environment variable.

from diotp import DiOTP, InvalidCodeError

client = DiOTP()  # reads DIOTP_API_KEY
otp = client.send("9876543210")  # country code 91 by default; keep otp.request_id

try:
    client.verify(otp.request_id, "482913")  # the code the user typed
    print("verified")
except InvalidCodeError:
    print("wrong code, try again")

Async:

import asyncio
from diotp import AsyncDiOTP


async def main() -> None:
    async with AsyncDiOTP() as client:
        otp = await client.send("9876543210")
        result = await client.verify(otp.request_id, "482913")
        print(result.verified_at)


asyncio.run(main())

Methods

Method Endpoint Returns
send(to, *, country_code=91, channel="sms", purpose="login", template=None, idempotency_key=None) POST /v1/otp/send SendResult
verify(request_id, code) POST /v1/otp/verify VerifyResult
resend(to, *, country_code=91, channel="sms", purpose="login", template=None) POST /v1/otp/send (helper) SendResult
me() GET /v1/me Account
usage(period=None) GET /v1/usage?period=YYYY-MM Usage
is_test_mode() GET /v1/me bool

On AsyncDiOTP every method is a coroutine. send_otp, verify_otp and resend_otp are other names for send, verify and resend.

The fields match Send an OTP and Verify an OTP: country_code is an integer (default 91) and code is a string of 4 to 10 characters.

  • to is the mobile number, digits only (6 to 15). For India, the 10-digit number without +91.
  • SendResult has request_id, channel, expires_at (a timezone-aware datetime, 5 minutes after sending) and idempotency_key.
  • VerifyResult has request_id, verified (always True) and verified_at. Every failure raises instead.
  • Account has client (id, name, status) and key (id, name, last_four).
  • Usage has period, attempts, accepted, billable_units and amount. amount is a decimal string such as "16.00", kept as a string so nothing is lost to floating point. Use decimal.Decimal(usage.amount).
  • Every result keeps the decoded JSON in .raw.

Resending a code

resend is a helper, not a separate endpoint. There is no resend endpoint in the API. It calls POST /v1/otp/send again with a new Idempotency-Key, so a new code is sent and you get a new request_id: verify against that one. The API allows one code to the same number every 30 seconds. Call resend sooner and it raises RateLimitError with code resend_cooldown, so show a 30-second resend timer in your app.

Configuration

from diotp import DiOTP

client = DiOTP(
    api_key="...",  # default: the DIOTP_API_KEY environment variable
    base_url="https://api-diotp.diorbit.com/v1",  # default
    timeout=10.0,  # seconds per attempt, default 10
    max_retries=2,  # default 2; 0 disables retries
    http_client=None,  # optional httpx.Client (httpx.AsyncClient for AsyncDiOTP)
)

If no key is passed and DIOTP_API_KEY is not set, the constructor raises ConfigurationError.

The key is never logged or included in error messages. repr(client) shows it masked, as dio_... and its last four characters.

Use the client as a context manager, or call close() (await aclose() for AsyncDiOTP) when done. A client you pass in through http_client is yours to close.

Error handling

Every error derives from DiOTPError, which has:

  • code: the stable error code, such as invalid_code. Branch on this.
  • status: the HTTP status, or None when there was no response.
  • message: a sentence for people. Its wording can change.
  • request_id: the id of the request (also the X-Request-Id header). Quote it to support.
Exception Status and codes
AuthenticationError 401 unauthorized
InsufficientBalanceError 402 insufficient_balance
PermissionDeniedError 403 account_suspended
TrialError test mode: 402 trial_used_up, 403 trial_restricted, 429 test_limit
InvalidCodeError (a ValidationError) 400 invalid_code
ValidationError 422 invalid_request, template_not_available
NotFoundError 404 not_found
ConflictError 409 already_verified, not_pending, idempotency_key_reused, channel_not_enabled
ExpiredError 410 expired
RateLimitError 429 resend_cooldown, phone_hourly_limit, phone_daily_limit, api_key_minute_limit, rate_limited, too_many_attempts
ServerError 5xx, such as 503 sending_unavailable
NetworkError no response: timeout, DNS failure, connection reset
ConfigurationError no API key, or an invalid setting
WebhookSignatureError a webhook failed verification

TrialError groups the three test-mode errors because they share a cause and a fix, even though their statuses differ. It is not a subclass of RateLimitError or PermissionDeniedError; check e.code or e.status if you need to tell them apart. A code this version does not know maps by HTTP status to the closest class and keeps the raw code.

RateLimitError.retry_after is the number of seconds from the Retry-After header, or None when the header is absent. The API does not send Retry-After today, so expect None.

from diotp import (
    DiOTP,
    ConflictError,
    ExpiredError,
    InvalidCodeError,
    RateLimitError,
    TrialError,
)

client = DiOTP()

try:
    client.verify(request_id, code)
except InvalidCodeError:
    ...  # wrong code: let the user try again (5 attempts per code)
except ExpiredError:
    ...  # more than 5 minutes passed: send a new code
except RateLimitError as e:
    if e.code == "too_many_attempts":
        ...  # locked: send a new code
except ConflictError as e:
    if e.code == "already_verified":
        ...  # treat the number as verified

The full list of codes is on API error codes.

Retries

The client retries automatically, with exponential backoff and full jitter (base 0.5 seconds, factor 2, capped at 8 seconds), up to max_retries times (default 2).

  • It retries only on network errors and 5xx responses.
  • It never retries a 4xx response, including 429. Read RateLimitError.retry_after and decide yourself.
  • send retries are safe: the same Idempotency-Key is reused on every retry of one call, so the API returns the first response instead of sending a second code. Pass your own idempotency_key to make retries across calls or processes safe too.
  • verify retries only on network errors and 502, 503 and 504. The server counts every verify attempt (five per code), so other 5xx responses are not retried.

Webhooks

DiOTP signs every webhook delivery. Verify it against the raw request body, before parsing it:

from diotp import WebhookSignatureError, verify_webhook_headers


# Flask
@app.post("/webhooks/diotp")
def diotp_webhook():
    try:
        event = verify_webhook_headers(request.get_data(), request.headers, WEBHOOK_SECRET)
    except WebhookSignatureError:
        return "", 400
    if event.event == "otp.verified":
        ...
    return "", 204

Or pass the headers yourself:

from diotp import verify_webhook

event = verify_webhook(
    raw_body,  # bytes or str, exactly as received
    headers["X-Diorbit-Signature"],
    headers["X-Diorbit-Timestamp"],
    secret,
    tolerance=300,  # seconds, default 300
)
  • The signature in X-Diorbit-Signature is the lowercase hex HMAC-SHA256 of "{timestamp}.{raw_body}", keyed with your endpoint's signing secret. X-Diorbit-Timestamp is Unix seconds.
  • The comparison is constant-time (hmac.compare_digest), and timestamps more than tolerance seconds from now are rejected.
  • The result is a WebhookEvent with event (otp.sent, otp.delivered, otp.failed or otp.verified), created_at, request_id, and channel and status when the event has them.
  • Any failure raises WebhookSignatureError.

Sandbox / test mode

Every new account starts in test mode. Test mode is the real API with one restriction, not a simulator: codes go only to the mobile number you verified at sign-up, as real SMS, with real request ids, expiry and attempt counting.

  • Sending to any other number raises TrialError with code trial_restricted (403).
  • When your free test messages are used up, sends raise TrialError with code trial_used_up (402).
  • A live account switched back to test mode in the dashboard has a daily allowance; past it, sends raise TrialError with code test_limit (429).
  • Rate limits apply in test mode too.

client.is_test_mode() returns True when me().client.status is trial or pending_review. A live account switched back to test mode in the dashboard still reports live, so is_test_mode() returns False for it; check the dashboard in that case. Going live needs no code change: the same key, base URL and requests keep working. More on test mode.

Tests

python -m venv .venv && . .venv/bin/activate
pip install -e . pytest pytest-asyncio
pytest                                         # unit tests, mocked HTTP, no API key needed
DIOTP_TEST_API_KEY=... pytest -m integration   # sandbox tests against the real API

The integration tests are deselected by default and skipped unless DIOTP_TEST_API_KEY is set. Without DIOTP_TEST_PHONE they send nothing that uses a test message; with it (your verified sign-up number) one test sends a real code.

Documentation

Full API documentation: https://diotp.diorbit.com/docs. Error codes: diotp.diorbit.com/docs/errors.

Licence

MIT. See LICENSE. Copyright (c) 2026 Diorbit Technologies LLP.

Metadata

Release files for diotp 1.0.0

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

Source distribution (sdist)

Source distribution for diotp 1.0.0
File Size Uploaded Provenance Actions
diotp-1.0.0.tar.gz 24.7 kB Without provenance Details for diotp-1.0.0.tar.gz

Built distribution (wheel)

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

Total release size: 43.6 kB

Release files / diotp-1.0.0.tar.gz

Download URL diotp-1.0.0.tar.gz
Size 24.7 kB
Tags Source
SHA-256 checksum
How to use checksums
a811eee7b8394c59ca23ad5a40189ca78dfd22b6d856ef673783f222888b8635
BLAKE2b-256 checksum
How to use checksums
ca97f261c2e3a46b78ff11cb399a937f8686528d9d6b8da42111d5ddd493f6da
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.15.2

Release files / diotp-1.0.0-py3-none-any.whl

Download URL diotp-1.0.0-py3-none-any.whl
Size 18.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
dea0b19719d7164008fcbe92580921420a38fe3705553d9db38476c7ad8fe7f6
BLAKE2b-256 checksum
How to use checksums
8e84d2d2b38ba8028452ae9562582f1f870d1f2b3b3cf51afd1592050e1d1129
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.15.2

Security for diotp 1.0.0

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.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

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