Skip to content

Interacting With The API

Rhys Bartels-Waller edited this page Jul 9, 2020 · 8 revisions

Interacting with the API

The API is served over TCP, leveraging the existing infrastructure of HTTP. GraphQL adds a powerful query layer to give you complete control over the request, including the shape of the data in the response. Detailed below are some approaches for connecting and interacting with the API, however there may be other ways more suited for your use-case.

Setup up a local stack using docker-compose, or use a public deployment.

GraphQL Playground to develop a query

The GUI provides a nice query development environment, complete with generated docs, and the schema to review. Once happy with the results, the query can be extracted as a formatted curl command.

Copy Curl button in GraphQL Playground

Example output

curl 'http://localhost:3100/' -H 'Accept-Encoding: gzip, deflate, br' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Connection: keep-alive' -H 'DNT: 1' -H 'Origin: http://localhost:3100' --data-binary '{"query":"query utxoAggregateValueLessThan (\n    $boundary: String\n){\n    utxos_aggregate( where: { value: { _lt: $boundary }}) {\n        aggregate {\n            avg { value }\n            count\n            max { value }\n            min { value }\n            sum { value }\n        }\n    }\n}","variables":{"boundary":"500"}}' --compressed

Command Line

graphqurl from the Hasura team is

curl for GraphQL with autocomplete, subscriptions and GraphiQL. Also a dead-simple universal javascript GraphQL client.

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

Request within app

const query = `
  query getTransactions(
    $limit: Int,
    $offset: Int,
    $where: Transaction_bool_exp
  ) {
     transactions(
      limit: $limit,
      offset: $offset,
      where: $where
    ) {
      fee
      block {
        number
      }
      id
    }
  }`

const limit = 100
const offset = 2
const where = {
  block: {
    number: {
      _gte: 50
      _lt: 100
    }
  }
}

fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  },
  body: JSON.stringify({
    query,
    variables: { limit, offset, where },
  })
})
  .then(r => r.json())
  .then(data => console.log(`Page ${offset} containing ${limit} transactions:', data))

Stateful client

Cardano Explorer serves as a working example.

Clone this wiki locally