# Python SDK

Search the catalog, buy, follow a purchase and verify its receipt from Python with the uapg_client package, a thin wrapper over the Abazi REST API.

The Python SDK (`uapg_client`) wraps the REST API. It is one class, `Gateway`, built on `httpx`. Each method is one HTTP call with the agent's credential as a Bearer token, so anything it does, any HTTP client can do the same way. See [Plain HTTP](/docs/agents/http-api).

## Before you start [#before-you-start]

| You need | Why |
| --- | --- |
| An agent credential (`agk_test_...`) | Created in the [Console](https://app.52-28-238-205.sslip.io) under **Agents > New agent**. Shown once. See [Get an agent credential](/docs/agents#get-an-agent-credential). |
| A signed mandate for that agent | Without one every purchase is denied with <ReasonCode code="MANDATE_MISSING" />. |
| Python 3.10 or later | With `httpx`, the SDK's only dependency. |

## Connect [#connect]

```python title="agent.py"
import os

from uapg_client import Gateway, GatewayError

gw = Gateway(os.environ["ABAZI_AGENT_KEY"], base_url="https://api.52-28-238-205.sslip.io")
```

`Gateway(api_key, base_url, timeout=70)`. The timeout is in seconds and is longer than the longest purchase wait (60 seconds), so a slow settlement never cuts the call short.

## Methods [#methods]

| Method | REST call | MCP tool |
| --- | --- | --- |
| `search(query=None, category=None, max_price_base_units=None, limit=20)` | `GET /v1/services` | `search_catalog` |
| `purchase(service_id=None, url=None, idempotency_key=None, task_id="sdk", input=None, purpose=None, wait_seconds=20)` | `POST /v1/payment-intents` | `request_purchase` |
| `status(intent_id)` | `GET /v1/payment-intents/{intent_id}` | `get_purchase_status` |
| `spending()` | `GET /v1/spending` | `get_spending_status` |
| `receipt(receipt_id)` | `GET /v1/receipts/{id}` | `get_receipt` |
| `verify_receipt(receipt_id_or_document)` | `GET /v1/receipts/{id}/verify` or `POST /v1/receipts/verify` | None: anyone can verify |

`search` returns the list of services. Every other method returns the JSON body as a `dict`.

## Verify [#verify]

```python title="agent.py"
for svc in gw.search("forecast"):
    print(svc["service_id"], svc["name"], svc["price_base_units"], svc["asset"], svc["tier"])

print(gw.spending())
```

Each service has a `service_id`, a `name`, the merchant and its `tier`, a price in base units (`50000` is 0.05 USDC), the `asset` and the networks it accepts. `spending()` returns what the agent has left to spend, what is reserved and what is spent, its `hard_cap` and `auto_threshold`, and when its mandate expires.

## First purchase [#first-purchase]

```python title="agent.py"
import time

svc = gw.search("forecast")[0]
try:
    res = gw.purchase(
        service_id=svc["service_id"],
        task_id="trip-plan-7",
        idempotency_key="trip-plan-7-forecast-1",
        input={"city": "Tbilisi"},
    )
    while res["status"] in ("submitted", "awaiting_approval"):
        time.sleep(res.get("poll_after_ms", 2000) / 1000)
        res = gw.status(res["intent_id"])
    print(res["status"], res.get("reason_code"))
    if res.get("receipt_id"):
        print(gw.verify_receipt(res["receipt_id"]))
except GatewayError as e:
    print(e.status, e.code, e.reason_code, e.details.get("next_action"))
```

Always pass your own `idempotency_key`. Without one the SDK makes a random key per call, so a retry after a timeout would be a new purchase instead of the same one.

### ALLOW [#allow]

`res["status"]` is `paid`, with `decision` `ALLOW`, the `resource`, the amount, asset, network and rail, and a `receipt_id`. `submitted` means the payment is still settling: poll `status()` after `poll_after_ms`.

### REQUIRE_APPROVAL [#require_approval]

`res["status"]` is `awaiting_approval`, with a `reason_code` such as <ReasonCode code="ABOVE_AUTO_THRESHOLD" />, <ReasonCode code="FIRST_PURCHASE" /> or <ReasonCode code="UNKNOWN_MERCHANT_LIMIT" />, an `approval_expires_at` and `poll_after_ms` of 5000. Abazi sends the approval link to the owner's approvers. Keep polling `status()` with the same `intent_id` until it is `paid` or `denied` (<ReasonCode code="APPROVAL_REJECTED" />, <ReasonCode code="APPROVAL_EXPIRED" />).

### DENY [#deny]

A denial raises `GatewayError` with `status` 403, `code` `POLICY_DENIED`, a `reason_code` such as <ReasonCode code="HARD_CAP_EXCEEDED" /> or <ReasonCode code="BUDGET_EXCEEDED" />, and `details` with `intent_id`, `retryable` and `next_action`. Report it and stop. Never retry a denial with a new key.

## Troubleshooting [#troubleshooting]

| Symptom | Cause and fix |
| --- | --- |
| `GatewayError` 401 `AGENT_CREDENTIAL_INVALID` | The credential is wrong, rotated or revoked (<ReasonCode code="AGENT_CREDENTIAL_INVALID" />). Stop and get a new one. |
| `GatewayError` 403 `FORBIDDEN`, "Agent credential required" | The client was built with an API key (`sk_test_...`) instead of an agent credential. Purchases need the agent's own credential. |
| `status` stays `awaiting_approval` | A person has not decided yet. Keep polling the same `intent_id`; do not start a new purchase. |
| `GatewayError` 409 `IDEMPOTENCY_CONFLICT` | The same `idempotency_key` was sent with a different body. Use a new key for a different purchase; reuse it only to retry the same one. |

## Next steps [#next-steps]

<Cards>
  <Card title="Plain HTTP" href="/docs/agents/http-api" description="The REST calls behind each method." />
  <Card title="Verify a receipt" href="/docs/guides/verify-a-receipt" description="What verify_receipt checks." />
  <Card title="Reason codes" href="/docs/api/errors-and-reason-codes" description="Every decision and its next action." />
  <Card title="All harnesses" href="/docs/agents" description="Compare the other ways to connect." />
</Cards>

