Please replace <Subgraph_name>
in the example with your own Subgraph name
query [operationName]([variableName]: [variableType]) {
[queryName]([argumentName]: [variableName]) {
# "{ ... }" express a Selection-Set, we are querying fields from `queryName`.
[field]
[field]
}
}
While the list of syntactic do’s and don’ts is long, here are the essential rules to keep in mind when it comes to writing GraphQL queries:
queryName
must only be used once per operation.field
must be used only once in a selection (we cannot query id
twice under token
)field
s or queries (like tokens
) return complex types that require a selection of sub-field. Not providing a selection when expected (or providing one when not expected - for example, on id
) will raise an error.Failing to follow the above rules will end with an error from the Graph API.
Unlike REST API, a GraphQL API is built upon a Schema that defines which queries can be performed.
For example, a query to get a block using the GetBlocks
query will look as follows:
query GetBlocks($id: ID!) {
blocks(id: $id) {
id
number
timestamp
}
}
It will return the following predictable JSON response ( when passing the correct *$id
*variable value ):
{
"data": {
"blocks": [
{
"id": "...",
"number": "...",
"timestamp": "..."
}
]
}
}
orderBy
parameter can be used to sort by specific properties. orderDirection
can be used to specify the sortfirst
parameter to page from the beginning of the collection. The skip
parameter can be used to skip entities and pagination.where
parameter to filter different propertiesexample:
query GetBlocks {
blocks(
first: 10
orderBy: id
orderDirection: desc
skip: 10
where: {number_gt: "17007257"}
) {
id
number
timestamp
}
}
For more features (such as time-travel queries, fulltext search queries), please refer to https://thegraph.com/docs/zh/querying/graphql-api/
Your application may need to query data for multiple entities, and you can send multiple queries in the same GraphQL request as follows:
query GetInfo {
blocks(
first: 10
orderBy: id
orderDirection: desc
where: {id: "0xffffc9887a687234b1076e3ccfb19d58b19746795ae13a5eea19286d6fc34f0b"}
) {
id
number
timestamp
}
submits(first: 10, orderBy: id, orderDirection: asc) {
id
from
amount
}
}
Using Graph Explorer will help you query data more easily
Query from the application can refer to: https://thegraph.com/docs/zh/querying/querying-from-an-application/