Async Migration¶
This guide explains how to use the new asynchronous client alongside the existing synchronous client, and when to choose each.
Overview¶
- Two clients are available:
RESTClient
(sync): for standard Python scripts and services.AsyncRESTClient
(async): for asyncio applications and concurrent workflows.- The sync client internally reuses a single async client on a background event loop to improve performance and reduce repeated initialization.
Do not use RESTClient in async code
Creating or using RESTClient
when an event loop is running raises a RuntimeError
. In async contexts, the AsyncRESTClient
must be used.
Staying on the sync client¶
If your code is synchronous, you can continue using RESTClient
with no changes.
from ethereal import RESTClient
config = {
"base_url": "https://api.etherealtest.net",
"chain_config": {
"rpc_url": "https://rpc.etherealtest.net",
"private_key": "your_private_key", # optional, required for signing
},
}
client = RESTClient(config)
# Property-like access remains for convenience
products = client.products
subaccounts = client.subaccounts
# Endpoints are mapped one-to-one
prices = client.list_market_prices(product_ids=[p.id for p in products])
# Cleanup when done
client.close()
Migrating to the async client¶
Use AsyncRESTClient
when running inside an event loop (e.g., FastAPI, asyncio tasks, async tests) or when you want to perform concurrent requests.
from ethereal import AsyncRESTClient
config = {
"base_url": "https://api.etherealtest.net",
"chain_config": {
"rpc_url": "https://rpc.etherealtest.net",
"private_key": "your_private_key", # optional, required for signing
},
}
client = await AsyncRESTClient.create(config)
# Methods are async
products = await client.products()
subaccounts = await client.subaccounts()
prices = await client.list_market_prices(product_ids=[p.id for p in products])
await client.close()
Choosing between sync and async¶
It is recommended that all users migrate to the async client for improved performance and scalability. The synchronous RESTClient
is made available for backward compatibility and ease of transition.