Exposing API with Hasura

Hasura is an easy way to expose indexed data using a GraphQL REST API. All you need is to download the latest Hasura engine docker image, set the database connection string, and run it.

Prerequisites

You will need the following for this guide:

  • We assume you already have an existing Dappetizer project with Postgresql database. Check out our Quick Start guide to learn how to set up one. PostgreSQL support needs to be also added.

  • Docker installed

Setting up Hasura

If you don't have a local Hasura instance running, you can spawn one using Docker:

docker run -d \
	--name dev-hasura \
	-e HASURA_GRAPHQL_DATABASE_URL=postgres://postgres:postgrespassword@host.docker.internal:5432/postgres \
	-e HASURA_GRAPHQL_ENABLE_CONSOLE=true \
	-p 8080:8080\
        hasura/graphql-engine:latest

Configuring Dappetizer

Dappetizer can automatically configure your Hasura instance to expose the entities you defined in your project. To do this, add the following section to your configuration file:

hasura: {
    url: 'http://localhost:8080/',
    autotrackEntities: true,
    dropExistingTracking: true,
}

The url specifies the Hasura instance Dappetizer will connect to on startup. The properties autotrackEntities and dropExistingTracking mean Dappetizer will automatically set up fields based on all known TypeORM entities. Check out the typedoc to learn more about this configuration section.

Testing in Hasura

You can run queries using the Hasura UI in your browser (for example, open http://localhost:8080 if you are running Hasura locally using Docker).

Example of simple GraphQL query of latest indexed block:

query MyQuery {
  blocks(limit: 1, order_by: {level: desc}) {
    level
    timestamp
    hash
    predecessor
  }
}

Should result output:

{
  "data": {
    "blocks": [
      {
        "level": 2086150,
        "timestamp": "2022-02-03T12:03:36",
        "hash": "BMcXd1JooP7migT7R3yhMQSFwg8thAQjeaNTvpkESRu8URppdh3",
        "predecessor": "BLnb5w4eiubfstHPxy8ACZdGpQiwxwQKNMeRtSjibE1zCU85XcQ"
      }
    ]
  }
}

You can also secure your Hasura instance by limiting access to your Hasura endpoint, controlling permissions, and setting query limits for particular objects. Read more in the Hasura documentation.

Last updated