Querying subgraphs in Python with Subgrounds
Leveraging the Subgrounds Python library to interact with subgraphs.
Overview
Overview
There are a multitude of ways to interact with subgraphs using Python. In this code snippet, we’ll review one of the more streamlined options: using the Subgrounds library to query data and save it in a pandas DataFrame
.
Subgrounds is a Python library by the Playgrounds team designed specifically to reduce friction present within python-based subgraph querying.
Environment setup
Environment setup
If you haven’t already, ensure that you’ve installed any version of Python greater than or equal to 3.10
, but less than 4.0
In this case, the only dependency here is subgrounds
, which you can install by running: pip install subgrounds
Defining the subgraph object
Defining the subgraph object
To define the subgraph object, we’ll need to first define sg
and CHAINSTACK_SUBGRAPH
.
sg
can be set equal toSubgrounds()
CHAINSTACK_SUBGRAPH
can be set equal to the query URL of a chosen subgraph you’ve deployed on Chainstack.
With these two variables defined, you can call the load_subgraph
function on sg
and pass in CHAINSTACK_SUBGRAPH
.
Defining the query
Defining the query
To begin building the query itself, we’ll need to define the following:
latest_pairs
, or a variable name of your choice, which will contain the query,subgraph.Query.{root field}
, in this case, we’ll be using thepairs
root field.- Additionally, you’ll need to define any query arguments. In this example, we’re ordering the results by timestamp in descending order and only returning the first 5 results. For this snippet, this is defined by
orderBy
,orderDirection
, andfirst
.
Understanding the response
Understanding the response
The response you get will vary significantly depending on the query parameters, specific return values, and the format in which you request the data.
In this case, due to the snippet using a pandas DataFrame
, we can see a truncated view of the table containing the data we queried.