Skip to content

Python SDK

Installation

pip install x402-client httpx eth-account

Basic Usage

from x402.client import X402Client
from eth_account import Account

wallet = Account.from_key("0x_your_key")
client = X402Client(wallet=wallet)

# Single price
eth = client.get("https://api.foursec.xyz/price/ETH").json()
print(f"ETH: ${eth['price_usd']}")

# Batch multiple tokens
for symbol in ['BTC', 'ETH', 'SOL']:
    data = client.get(f"https://api.foursec.xyz/price/{symbol}").json()
    print(f"{symbol}: ${data['price_usd']}")

Error Handling

import httpx

try:
    response = client.get("https://api.foursec.xyz/price/XYZ")
except httpx.HTTPStatusError as e:
    if e.response.status_code == 404:
        print("Symbol not found")
    elif e.response.status_code == 429:
        print("Rate limited, retrying...")

Async Usage

import asyncio
import httpx

async def fetch_prices():
    async with httpx.AsyncClient() as http:
        tasks = [
            client.aget(f"https://api.foursec.xyz/price/{s}")
            for s in ['BTC', 'ETH', 'SOL']
        ]
        results = await asyncio.gather(*tasks)
        return [r.json() for r in results]

prices = asyncio.run(fetch_prices())

Caching Wrapper

import time

class CachedClient:
    def __init__(self, api_client, ttl=30):
        self.api = api_client
        self.ttl = ttl
        self.cache = {}

    def get(self, url):
        now = time.time()
        if url in self.cache and (now - self.cache[url]['time']) < self.ttl:
            return self.cache[url]['data']
        data = self.api.get(url).json()
        self.cache[url] = {'data': data, 'time': now}
        return data

Redis Integration

import redis
import json

cache = redis.Redis()

def get_price(symbol):
    key = f"price:{symbol}"
    cached = cache.get(key)
    if cached:
        return json.loads(cached)
    data = client.get(f"https://api.foursec.xyz/price/{symbol}").json()
    cache.setex(key, 30, json.dumps(data))
    return data

Released under the MIT License.