Learn How to Use Cardano-graphql to Query Cardano Blockchain Data

What is Cardano GraphQL | AdaPulse

In this article, we’ll show you how to use cardano-graphql to query the Cardano blockchain data using GraphQL, and give some examples of common queries and responses. But before that, here’s a quick primer on GraphQL and the Cardano-graphql.

What is GraphQL and the Cardano-graphql?

GraphQL is a query language and a runtime system for accessing data from various sources, such as databases, APIs, or blockchains. It allows users to specify the exact data they need, and get a response in a structured and predictable format. GraphQL also supports features such as pagination, filtering, sorting, and subscriptions, which make it easier to work with large and complex data sets.

Cardano-graphql is a cross-platform, typed, and queryable API for Cardano, which provides a GraphQL interface to all the blockchain data. Using Cardano-graphql, users can query the blockchain state, transactions, addresses, stake pools, assets, metadata, and more, using GraphQL queries. It’s a convenient choice for client applications based on web technologies, such as applications written in JavaScript, or any other browser-based languages, that use HTTP/REST APIs to talk to other services.

Prerequisites

To use cardano-graphql, you need to have the following components installed and running:

  • A Cardano node, which is the core component of the Cardano network, and connects to other nodes to maintain the blockchain. You can run your own node, or use a public node, such as Dandelion.
  • A cardano-db-sync component, which synchronizes data from the Cardano node to a PostgreSQL database, and provides a SQL interface to the blockchain data.
  • A cardano-graphql component, which exposes a GraphQL API to the PostgreSQL database, and provides a query interface to the blockchain data.

You can find the installation and configuration instructions for these components on the Cardano documentation website. Alternatively, you can use a hosted service, such as Blockfrost, which provides a cardano-graphql endpoint, along with other APIs, for accessing the Cardano blockchain data.

Querying cardano-graphql

To query cardano-graphql, you need to send a POST request to the cardano-graphql endpoint, with a JSON payload that contains the query and the variables. The query is a string that follows the GraphQL syntax, and specifies the data fields and the filters that you want to retrieve. In the request, you can add optional variables to pass dynamic values to the query. The response is a JSON object that contains the data or errors in the request, if any.

You can use any HTTP client, such as curl, to send the request and receive the response. For example, the following curl command sends a query to the cardano-graphql endpoint, and prints the response:

curl -X POST -H "Content-Type: application/json" -d '{"query": "{ cardano { tip { number slotNo epoch { number } } } }"}' http://localhost:3100/graphql

The response is:

{
  "data": {
    "cardano": {
      "tip": {
        "number": 12345678,
        "slotNo": 45678901,
        "epoch": {
          "number": 321
        }
      }
    }
  }
}

The response shows the number, slot number, and epoch number of the tip of the blockchain, which is the latest block that the node has seen.

You can also use a graphical user interface, such as GraphQL Playground, to interact with the cardano-graphql endpoint. GraphQL Playground provides a web-based IDE, where you can write, run, and debug GraphQL queries, and explore the schema and the documentation of the API. You can access GraphQL Playground by opening the cardano-graphql endpoint URL in your browser, such as http://localhost:3100/graphql.

Examples of cardano-graphql queries

Here are some examples of common cardano-graphql queries and responses. You can try these queries on your own cardano-graphql endpoint, or on the Dandelion GraphQL playground.

Query the details of a block by its hash

To query the details of a block by its hash, you can use the blocks query, and pass the hash as a filter. For example, the following query retrieves the details of the block with the hash f58152cafbd25e618433eae52f72bb419e00efe91b5cf7c74a93f8c29cbb2e7b:

query getBlock ($hash: Hash32Hex!) {
  blocks (limit: 1, where: { hash: { _eq: $hash } }) {
    forgedAt
    slotLeader {
      description
    }
    epochNo
    hash
    number
    size
    slotNo
    transactions_aggregate {
      aggregate {
        count
        sum {
          totalOutput
        }
      }
    }
  }
}

The query uses a variable $hash to pass the hash value, and specifies the fields that it wants to retrieve, such as the forged time, the slot leader, the epoch number, the block number, the size, the slot number, and the transactions count and sum. The response is:

{
  "data": {
    "blocks": [
      {
        "forgedAt": "2023-03-22T10:44:51Z",
        "slotLeader": {
          "description": "Dandelion"
        },
        "epochNo": 321,
        "hash": "f58152cafbd25e618433eae52f72bb419e00efe91b5cf7c74a93f8c29cbb2e7b",
        "number": 12345678,
        "size": 1234,
        "slotNo": 45678901,
        "transactions_aggregate": {
          "aggregate": {
            "count": 10,
            "sum": {
              "totalOutput": "1000000000000"
            }
          }
        }
      }
    ]
  }
}

The response shows the details of the block, such as the forged time, the slot leader, the epoch number, the block number, the size, the slot number, and the transactions count and sum.

Query the details of a transaction by its hash

To query the details of a transaction by its hash, you can use the transactions query, and pass the hash as a filter. For example, the following query retrieves the details of the transaction with the hash f58152cafbd25e618433eae52f72bb419e00efe91b5cf7c74a93f8c29cbb2e7b:

query getTransaction ($hash: Hash32Hex!) {
  transactions (limit: 1, where: { hash: { _eq: $hash } }) {
    block {
      epochNo
      hash
      number
      slotNo
    }
    deposit
    fee
    hash
    includedAt
    mint {
      asset {
        assetName
        decimals
        description
        fingerprint
        name
        policyId
        ticker
      }
      quantity
    }
    inputs {
      address
      sourceTxHash
      sourceTxIndex
      value
      tokens {
        asset {
          assetName
          decimals
          description
          fingerprint
          name
          policyId
          ticker
        }
        quantity
      }
    }
    metadata {
      key
      value
    }
    outputs {
      address
      index
      value
      tokens {
        asset {
          assetName
          decimals
          description
          fingerprint
          name
          policyId
          ticker
        }
        quantity
      }
    }
    totalOutput
    withdrawals {
      address
      amount
    }
  }
}

The query uses a variable $hash to pass the hash value, and specifies the fields that it wants to retrieve, such as the block, the deposit, the fee, the hash, the included time, the mint, the inputs, the metadata, the outputs, the total output, and the withdrawals. The response is:


{
"data": {
"transactions": [
{
"block": {
"epochNo": 321,
"hash": "f58152cafbd25e618433eae52f72bb419e00efe91b5cf7c74a93f8c29cbb2e7b",
"number": 12345678,
"slotNo": 45678901
},
"deposit": "0",
"fee": "200000",
"hash": "f58152cafbd25e618433eae52f72bb419e00efe91b5cf7c74a93f8c29cbb2e7b",
"includedAt": "2023-03-22T10:44:51Z",
"mint": [],
"inputs": [
{
"address": "addr1q9w7jzgjy7xj9p9k6q0n0x0xj9y9x4wq9w7jzgjy7xj9p9k6q0n0x0xj9y9x4wq9w7jzgjy7xj9p9k6q0n0x0xj9y9x4wq9w

Query the details of an address by its value

To query the details of an address by its value, you can use the addresses query, and pass the value as a filter. In the following query, we retrieve the details of the address with the value addr1q9w7jzgjy7xj9p9k6q0n0x0xj9y9x4wq9w7jzgjy7xj9p9k6q0n0x0xj9y9x4wq9w7jzgjy7xj9p9k6q0n0x0xj9y9x4wq9w:

query getAddress ($value: String!) {
  addresses (limit: 1, where: { value: { _eq: $value } }) {
    value
    summary {
      assetBalances {
        asset {
          assetName
          decimals
          description
          fingerprint
          name
          policyId
          ticker
        }
        quantity
      }
      utxosCount
    }
    transactions {
      hash
      fee
      includedAt
    }
  }
}

The query uses a variable $value to pass the value, and specifies the fields that it wants to retrieve, such as the value, the summary, the asset balances, the utxos count, and the transactions. The response is:

{
  "data": {
    "addresses": [
      {
        "value": "addr1q9w7jzgjy7xj9p9k6q0n0x0xj9y9x4wq9w7jzgjy7xj9p9k6q0n0x0xj9y9x4wq9w7jzgjy7xj9p9k6q0n0x0xj9y9x4wq9w",
        "summary": {
          "assetBalances": [
            {
              "asset": {
                "assetName": "ADA",
                "decimals": 6,
                "description": "Cardano native token",
                "fingerprint": "asset1rjklcrnsdzqp65wjgrg55sy9723kw09mlgvlc3",
                "name": "ADA",
                "policyId": "ada",
                "ticker": "ADA"
              },
              "quantity": "1000000000"
            }
          ],
          "utxosCount": 1
        },
        "transactions": [
          {
            "hash": "f58152cafbd25e618433eae52f72bb419e00efe91b5cf7c74a93f8c29cbb2e7b",
            "fee": "200000",
            "includedAt": "2023-03-22T10:44:51Z"
          }
        ]
      }
    ]
  }
}

The response shows the details of the address, such as the value, the summary, the asset balances, the utxos count, and the transactions.

Query the details of an asset by its fingerprint

To query the details of an asset by its fingerprint, you can use the assets query, and pass the fingerprint as a filter. Using the following query, we retrieve the details of the asset with the fingerprint asset1rjklcrnsdzqp65wjgrg55sy9723kw09mlgvlc3:

query getAsset ($fingerprint: String!) {
  assets (limit: 1, where: { fingerprint: { _eq: $fingerprint } }) {
    assetName
    decimals
    description
    fingerprint
    logo
    name
    policyId
    ticker
    metadata {
      name
      value
    }
  }
}

The query uses a variable $fingerprint to pass the fingerprint, and specifies the fields that it wants to retrieve, such as the asset name, the decimals, the description, the fingerprint, the logo, the name, the policy id, the ticker, and the metadata. A successful response returns the following:

{
  "data": {
    "assets": [
      {
        "assetName": "ADA",
        "decimals": 6,
        "description": "Cardano native token",
        "fingerprint": "asset1rjklcrnsdzqp65wjgrg55sy9723kw09mlgvlc3",
        "logo": null,
        "name": "ADA",
        "policyId": "ada",
        "ticker": "ADA",
        "metadata": []
      }
    ]
  }
}

The response shows the details of the asset, such as the asset name, the decimals, the description, the fingerprint, the logo, the name, the policy id, the ticker, and the metadata.

Conclusion

In this article, we introduced cardano-graphql, a cross-platform, typed, and queryable API for Cardano, which provides a GraphQL interface to all the blockchain data. We also shown how to use cardano-graphql to query the Cardano blockchain data using GraphQL, and gave some examples of common queries and responses.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts