Python
Python SDK
Learn how to connect to Reverix's API using Python.
Installation
First, install the required dependencies using pip:
pip install requests
Basic Setup
Create a new API client class:
import requests from typing import Optional, Dict, Any class ReverixClient: def __init__(self, api_key: str): self.base_url = "https://api.reverixy.ai/v1" self.session = requests.Session() self.session.headers.update({ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" })
Example: Get Token Price
Add a method to fetch token prices:
def get_token_price( self, contract_address: str, network_id: int = 1 ) -> Dict[str, Any]: """ Fetch the current price of a token. Args: contract_address: The token's contract address network_id: Network ID (default: 1 for Ethereum mainnet) Returns: Dict containing price and token information """ params = { "address": contract_address, "network": network_id } response = self.session.get( f"{self.base_url}/blockchain/token/price", params=params ) response.raise_for_status() return response.json() # Example usage client = ReverixClient("YOUR_SECRET_KEY") usdc_address = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" price = client.get_token_price(usdc_address) print(f"USDC Price: {price}")
Error Handling
Implement proper error handling with custom exceptions:
class ReverixyError(Exception): """Base exception for Reverix API errors""" pass class ReverixAPIError(ReverixError): def __init__(self, message: str, status_code: int): self.status_code = status_code super().__init__(message) def handle_api_error(response: requests.Response) -> None: """Handle API errors based on status code""" try: response.raise_for_status() except requests.exceptions.HTTPError as e: error_msg = response.json().get("error", str(e)) if response.status_code == 401: raise ReverixAPIError("Invalid API key", 401) elif response.status_code == 429: raise ReverixAPIError("Rate limit exceeded", 429) elif response.status_code >= 500: raise ReverixAPIError("Server error", response.status_code) raise ReverixAPIError(error_msg, response.status_code)
Async Support
For async applications, use aiohttp:
import aiohttp import asyncio async def get_token_price_async( contract_address: str, api_key: str, network_id: int = 1 ) -> Dict[str, Any]: async with aiohttp.ClientSession() as session: session.headers.update({ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" }) async with session.get( "https://api.reverix.ai/v1/blockchain/token/price", params={ "address": contract_address, "network": network_id } ) as response: response.raise_for_status() return await response.json()
Rate Limiting
The API has a rate limit of 5 requests per second per API key. Here's how to handle it:
import time from typing import Callable, TypeVar, Any T = TypeVar('T') def with_retry(func: Callable[..., T], max_retries: int = 3) -> T: """Decorator to handle rate limiting with exponential backoff""" def wrapper(*args, **kwargs): retries = 0 while retries < max_retries: try: return func(*args, **kwargs) except ReverixAPIError as e: if e.status_code == 429: retries += 1 delay = min(1 * (2 ** retries), 10) time.sleep(delay) continue raise raise ReverixAPIError("Max retries exceeded", 429) return wrapper @with_retry def get_token_price(self, contract_address: str, network_id: int = 1) -> Dict[str, Any]: """ Fetch token price with automatic retry on rate limit """ params = { "address": contract_address, "network": network_id } response = self.session.get( f"{self.base_url}/blockchain/token/price", params=params ) handle_api_error(response) return response.json()
Rate Limit Note
The rate limit is enforced per API key, not per connection. If you need higher limits, consider upgrading your plan or implementing request queuing in your application.
Last updated