How to Subscribe to Real-Time Data Stream using Bitquery API and Python GraphQL Client

We will use the python_graphql_client package to get real-time data from the Streaming APIs.
Here’s a step-by-step tutorial on how to use this code:

Step 1: Import required libraries

from python_graphql_client import GraphqlClient
from requests.auth import HTTPBasicAuth
import http.client
import asyncio

This code block imports the GraphqlClient library, HTTPBasicAuth, and http.client libraries required for this script.

Step 2: Set up authentication

auth = HTTPBasicAuth('', 'YOUR API KEY')

The Bitquery API requires authentication, and the above code sets up the authentication using HTTPBasicAuth with the API key as the password.

Step 3: Set up the GraphQL client

ws = GraphqlClient(endpoint="wss://",auth=auth)

This code sets up a GraphqlClient instance with the Bitquery WebSocket endpoint and authentication.

Step 4: Define the subscription callback function

def callback(_id, data):
  print("got new data..")
  print(f"msg id: {_id}. data: {data}")

This function is called every time new data is received from the WebSocket stream. The function takes two arguments - _id and data - where _id is the message ID and data is the actual message payload.

Step 5: Define the GraphQL subscription query

query = """
 subscription {
    EVM(network: bsc) {
      Transfers {
        Block {
        Transfer {
          Currency {

This code block defines the GraphQL subscription query, which is sent to the Bitquery API to subscribe to the Binance Smart Chain network’s Transfer events.

Step 6: Make an asynchronous subscription request, handle=print))

This code block makes an asynchronous subscription request to the Bitquery API with the defined subscription query and the handle parameter set to print. The handle parameter specifies the function that should be called when new data is received.

Finally, the method is called to run the subscription request asynchronously.

That’s it! By running this code, you should be able to see the data in your terminal as shown below.

1 Like