Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.swiftpay.finance/llms.txt

Use this file to discover all available pages before exploring further.

The swiftpay-api-client is a production-ready Python SDK for the SwiftPay REST API. It supports both synchronous and asynchronous code with full type hints and Pydantic v2 models.

Features

  • Sync and AsyncSwiftPay for sync code, AsyncSwiftPay for asyncio (FastAPI, async workers)
  • Auth-aware — Methods needing a secret key raise errors at call time, not silent 401s
  • Typed errors — Each HTTP status maps to a discriminated subclass
  • Type-safe — Full type hints with Pydantic v2 models
  • Minimal deps — Only httpx and pydantic

Installation

pip install swiftpay-api-client
Requires Python 3.10+.

Quick Start

Synchronous

from swiftpay import SwiftPay

client = SwiftPay(secret_key="sk_live_...")

result = client.invoices.create(
    amount="100.00",
    token="USDC",
    network="ethereum",
    recipients={"evm": "0xYourWallet..."},
    external_ref="order_8675309",
)
print("New" if result.created else "Existing", result.invoice.id)

Asynchronous

import asyncio
from swiftpay import AsyncSwiftPay

async def main() -> None:
    async with AsyncSwiftPay(secret_key="sk_live_...") as client:
        chains = await client.utils.list_chains()
        for c in chains:
            print(c.id, c.chain_id)

asyncio.run(main())

Configuration

SwiftPay(
    secret_key="sk_live_...",                 # optional — required only for secret-scoped modules
    base_url="https://api.swiftpay.finance",  # optional, defaults to production
    timeout=30.0,                              # optional, seconds
    http_client=...,                           # optional, inject your own httpx.Client
)

Modules

ModuleAuthMethods
client.utilsnonelist_chains(), list_tokens()
client.invoicessecret keycreate(), list(), get(), list_transactions(), rescan()
client.x402.facilitatornonesupported(), verify(), settle(), payment_status()
client.x402.endpointssecret keyregister(), list(), deactivate(), requirements(), requirements_by_id()

Utilities

chains = await client.utils.list_chains()
tokens = await client.utils.list_tokens()

Invoices

# Create invoice
result = await client.invoices.create(
    amount="100.00",
    token="USDC",
    network="ethereum",
    recipients={"evm": "0xYourWallet..."},
    external_ref="order_12345",      # optional, for deduplication
    expires_in=3600,                 # optional, seconds
    metadata={"order_id": "12345"},  # optional, custom data
)

# List invoices
invoices = await client.invoices.list(page=1, limit=50)

# Get single invoice
invoice = await client.invoices.get(invoice_id)

# Get transactions
transactions = await client.invoices.list_transactions(invoice_id)

# Rescan for payments
await client.invoices.rescan(
    invoice_id,
    chain="ethereum",
    tx_hash="0x...",      # optional
    from_block=18000000,  # optional
)

x402 Facilitator

# Check support
supported = await client.x402.facilitator.supported()

# Verify payment
verified = await client.x402.facilitator.verify(
    x402_version="v1",
    payment_payload={...},
    payment_requirements={...},
)

# Settle payment
response = await client.x402.facilitator.settle(
    x402_version="v1",
    payment_payload={...},
    payment_requirements={...},
)

# Check payment status
status = await client.x402.facilitator.payment_status(nonce="...")
settle() returns a SettlementResponse for both 200 (settled) and 422 (settlement failed). Always check result.success before assuming settlement completed. Other 4xx/5xx responses raise exceptions.

x402 Endpoints

# Register endpoint
endpoint = await client.x402.endpoints.register(
    endpoint_url="https://api.example.com/v1/analyze",
    asset="USDC",
    network="ethereum",
    amount_usd="0.05",
    description="AI analysis endpoint",
)

# List endpoints
endpoints = await client.x402.endpoints.list()

# Deactivate endpoint
await client.x402.endpoints.deactivate(endpoint_id)

# Get requirements
requirements = await client.x402.endpoints.requirements(
    url="https://api.example.com/v1/analyze"
)

# Get requirements by ID
requirements = await client.x402.endpoints.requirements_by_id(endpoint_id)

Error Handling

The SDK provides typed exceptions for error scenarios:
from swiftpay import SwiftPay
from swiftpay.errors import (
    SwiftPayError,
    SwiftPayValidationError,
    SwiftPayAuthError,
    SwiftPayNotFoundError,
    SwiftPayConfigError,
    SwiftPayServerError,
)

client = SwiftPay(secret_key="sk_live_...")

try:
    await client.invoices.create(
        amount="",            # Invalid
        token="USDC",
        network="ethereum",
        recipients={"evm": "0x..."},
    )
except SwiftPayValidationError as e:
    print(f"Validation error: {e.details}")
except SwiftPayAuthError:
    print("Auth failed — check your secret key")
except SwiftPayConfigError:
    print("Configuration error — missing required field")
except SwiftPayServerError as e:
    print(f"Server error: {e.status}")
except SwiftPayError as e:
    print(f"SwiftPay error: {e.message} (trace: {e.trace_id})")

FastAPI Example

from fastapi import FastAPI, HTTPException
from swiftpay import AsyncSwiftPay

app = FastAPI()
client = AsyncSwiftPay(secret_key="sk_live_...")

@app.post("/create-invoice")
async def create_invoice(amount: str, reference: str):
    try:
        result = await client.invoices.create(
            amount=amount,
            token="USDC",
            network="ethereum",
            recipients={"evm": "0x..."},
            external_ref=reference,
        )
        return {"invoice_id": result.invoice.id, "created": result.created}
    except SwiftPayValidationError as e:
        raise HTTPException(status_code=400, detail=str(e.details))
    except SwiftPayError as e:
        raise HTTPException(status_code=500, detail=str(e.message))

Full API Reference

For complete type definitions, advanced patterns, and parameter details, see the official Python SDK on PyPI. All APIs are in v0.1.0-beta — stable and production-ready.