Querying Horizon

py-stellar-sdk gives you access to all the endpoints exposed by Horizon.

Building requests

py-stellar-sdk uses the Builder pattern to create the requests to send to Horizon. Starting with a Server object, you can chain methods together to generate a query. (See the Horizon reference documentation for what methods are possible.)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from stellar_sdk import Server

server = Server(horizon_url="https://horizon-testnet.stellar.org")

# get a list of transactions that occurred in ledger 1400
transactions = server.transactions().for_ledger(1400).call()
print(transactions)

# get a list of transactions submitted by a particular account
transactions = server.transactions() \
    .for_account(account_id="GASOCNHNNLYFNMDJYQ3XFMI7BYHIOCFW3GJEOWRPEGK2TDPGTG2E5EDW") \
    .call()
print(transactions)

Once the request is built, it can be invoked with call() or with stream(). call() will return the response given by Horizon.

Streaming requests

Many requests can be invoked with stream(). Instead of returning a result like call() does, stream() will return an EventSource. Horizon will start sending responses from either the beginning of time or from the point specified with cursor(). (See the Horizon reference documentation to learn which endpoints support streaming.)

For example, to log instances of transactions from a particular account:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from stellar_sdk import Server

server = Server(horizon_url="https://horizon-testnet.stellar.org")
account_id = "GASOCNHNNLYFNMDJYQ3XFMI7BYHIOCFW3GJEOWRPEGK2TDPGTG2E5EDW"
last_cursor = 'now'  # or load where you left off


def tx_handler(tx_response):
    print(tx_response)


for tx in server.transactions().for_account(account_id).cursor(last_cursor).stream():
    tx_handler(tx)