# Python

> A standard-library Python client, a sandbox demo, and Flask endpoints.

Python 3.8+, no dependencies for the client. The client and demo are tested against the API's sandbox on every change.

## Client

```python title="examples/python/otp_ps.py"
"""OTP.ps client for Python 3.8+ (standard library only). Server-side only.

    OTP_PS_API_KEY=otp_test_...   (sandbox) or otp_live_... (real messages)
    OTP_PS_BASE_URL=https://otp.ps   (optional)
"""
import json
import os
import urllib.error
import urllib.request


class OtpPsError(Exception):
    def __init__(self, status, body):
        body = body or {}
        super().__init__(body.get("message") or f"OTP.ps answered HTTP {status}")
        self.status = status
        self.code = body.get("error", "unknown")  # e.g. invalid_phone, rate_limited
        self.retry_after = body.get("retry_after")  # seconds, for rate_limited


class OtpPs:
    def __init__(self, api_key=None, base_url=None, timeout=15):
        self.key = api_key or os.environ.get("OTP_PS_API_KEY")
        if not self.key:
            raise RuntimeError("OTP_PS_API_KEY is not set")
        self.base = (base_url or os.environ.get("OTP_PS_BASE_URL") or "https://otp.ps").rstrip("/")
        self.timeout = timeout

    def _request(self, method, path, body=None, headers=None):
        req = urllib.request.Request(
            f"{self.base}/api/v1{path}",
            method=method,
            data=json.dumps(body).encode() if body is not None else None,
            headers={"Authorization": f"Bearer {self.key}", "Content-Type": "application/json", **(headers or {})},
        )
        try:
            with urllib.request.urlopen(req, timeout=self.timeout) as res:
                return json.loads(res.read())
        except urllib.error.HTTPError as e:
            try:
                data = json.loads(e.read())
            except ValueError:
                data = None
            raise OtpPsError(e.code, data) from None

    def send_code(self, phone, purpose="verify", locale=None, idempotency_key=None):
        """Sends a code. Returns the verification (with test_code when using a test key)."""
        body = {"phone": phone, "purpose": purpose}
        if locale:
            body["locale"] = locale
        return self._request("POST", "/verify/send", body, {"Idempotency-Key": idempotency_key} if idempotency_key else None)

    def check_code(self, verification_id, code):
        """Checks what the customer typed. Trust only result["valid"] is True."""
        return self._request("POST", "/verify/check", {"id": verification_id, "code": str(code)})

    def balance(self):
        return self._request("GET", "/balance")
```

## Sandbox demo

```bash
OTP_PS_API_KEY=otp_test_… python demo.py
```

```python title="examples/python/demo.py"
"""Sandbox walk-through:  OTP_PS_API_KEY=otp_test_... python demo.py"""
import os
import sys
import uuid

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from otp_ps import OtpPs, OtpPsError  # noqa: E402

otp = OtpPs()
sent = otp.send_code("0599000001", locale="en", idempotency_key=f"py-demo-{uuid.uuid4()}")
print(f"Sent {sent['id']} to {sent['to']} (status {sent['status']})")

wrong = otp.check_code(sent["id"], "0000")
print(f"Wrong code: valid={wrong['valid']}, attempts_left={wrong['attempts_left']}")

right = otp.check_code(sent["id"], "1234")  # the sandbox number's fixed code
print(f"Right code: valid={right['valid']}, status={right['status']}")

try:
    otp.send_code("0599000002")  # sandbox: the gateway refuses the message
except OtpPsError as e:
    print(f"Refused message: {e.code} (status {e.status})")
```

## Flask endpoints

```python title="examples/python/flask_app.py"
"""Flask endpoints for a website form (pip install flask).

The verification id and the number stay in the server-side session data;
the browser only learns that a code was sent.
"""
import os

from flask import Flask, jsonify, request, session

from otp_ps import OtpPs, OtpPsError

app = Flask(__name__)
app.secret_key = os.environ["FLASK_SECRET_KEY"]  # signs the session cookie
otp = OtpPs()


@app.post("/api/otp/send")
def send():
    # Add your own per-visitor limit here (e.g. Flask-Limiter), so nobody can drain your balance.
    phone = str((request.json or {}).get("phone", ""))
    locale = "en" if (request.json or {}).get("locale") == "en" else "ar"
    try:
        v = otp.send_code(phone, purpose="verify", locale=locale)
    except OtpPsError as e:
        return jsonify(error=e.code, retryAfter=e.retry_after), 429 if e.code == "rate_limited" else 400
    session["otp_pending"] = {"id": v["id"], "phone": phone}
    return jsonify(sent=True, to=v["to"], expiresAt=v["expires_at"])


@app.post("/api/otp/check")
def check():
    pending = session.get("otp_pending")
    if not pending:
        return jsonify(error="no_code"), 400
    try:
        r = otp.check_code(pending["id"], str((request.json or {}).get("code", "")))
    except OtpPsError as e:
        return jsonify(error=e.code), 400
    if r["valid"] is True:
        session.pop("otp_pending")
        session["verified_phone"] = pending["phone"]  # trust this, set on the server
        return jsonify(verified=True)
    if r["status"] != "pending":
        session.pop("otp_pending")
    return jsonify(verified=False, status=r["status"], attemptsLeft=r["attempts_left"]), 400
```

For Django, the same two views apply: keep `{"id", "phone"}` in `request.session`, and set the verified number on the user only after `valid` is `True`.
