Kickstart GraphQL Backends with Hasura

A complete guide with the Developer’s perspective

GraphQL has become one of the popular alternatives for REST APIs. However, developing a GraphQL API from scratch has a steeper learning curve, along with the overheads of bootstrapping the project.

But what if there is a GraphQL API platform with a simplified programming model to kickstart?

This is where the savior Hasura comes into play.

So in this article, I will guide you through the path to develop an efficient GraphQL backend with Hasura.

What makes Hasura UNIQUE? ?

Hasura is an Open Source service that enables the frontends to access the data over a real-time GraphQL API.

The aim is to make life easier for developers and build applications faster. However, one of the common challenges for GraphQL is managing the database tables and the GraphQL schema mappings.

Hasura automates the management by pointing to your database and generating the GraphQL Schemas by going through the tables and relationships in your database.

You can even connect remote schemas (integrations) like Payment Gateways, making the Hasura service a single source of truth for your data.

Hasura also provides some unique features like

  • Actions: Actions allow you to add custom business logic to Hasura. Actions will enable you to create a Query or Mutation that you can execute to fire an action.
  • Events: Events allow you to trigger a REST endpoint call when some changes are introduced to your database (e.g., the Serverless function sends email). These events can be scheduled as well, like Corn jobs.

In addition,

  1. Hasura connects to your databases, REST endpoints, GraphQL endpoints, and 3rd party Services to a unified and real-time Grpahql API.
  2. Provides a cloud service that gives you a fully managed and production-ready GrpahQL API as a service.

Hasura has some powerful capabilities like Caching and Subscriptions for real-time data with faster load time.

Using it in Practice: Let’s Build an App

In this section, let’s see how we can build a GraphQL application using Hasura. This application will maintain a collection of Pokemons ?.

01. Create a project in the Hasura cloud.

Hasura Project

We will be using a Postgres Database for this demo application.

Hasura allows you to connect to your own Postgres DB or connect your Heroku account, creating a Postgres DB on Heroku.

In addition, Hasura provides a decent UI for database management.

Here you can make the schemas and table for your application.

Connecting Heroku and create Hasura

02. Moving into GraphQL playground.

Now that we have created our database on Heroku via Hasura. Let’s move towards the Hasura Dashboard, where you can find the GraphQL playground.

Here you can see that the schemas are automatically generated with the Queries and Mutation for the table you created in Postgres DB.

Hasura GraphQL Playground

In this application, we will be using several features provided by Hasura. They are Events and Actions, which will allow you to connect to external data sources or trigger events whenever some changes are introduced to your Postgres DB.

Demo application Architecture

As you can see in the above diagram, I’m using some External services like Pokemon API and Serverless functions (using Netlify f

unctions) for fetching and saving data.

03 Create the frontend application.

Now let’s create our frontend application which will consume the GraphQL endpoints in Hasura. We will be using create-react-app with URQL, which is a highly customizable and versatile GraphQL client.

Use the following command to create the React application.

npx create-react-app hasura-pokemon

04. Installing dependencies and connect the application.

Inside the project root, execute the following command.

yarn add urq graphql l@astrajs/collections antd node-fetch

This command will install the libraries for the URQL GraphQL client and some dependencies for our Netlify functions.

Now that the dependencies are installed, let’s connect to our Hasura GraphQL server. To do that, add the following code snippet inside the index.js file.

import { createClient, Provider } from 'urql';
const client = createClient({
url: process.env.REACT_APP_HASURA_URL,
fetchOptions: () => {
return {
headers: {
'content-type': 'application/json',
'x-hasura-admin-secret': process.env.REACT_APP_HASURA_SECRET
},
};
},
});
ReactDOM.render(
<Provider value={client}>
<App />
</Provider>,
document.getElementById('root')
);

Note that we have used some environmental variables to pass the Hasura Secret and Hasura GraphQL endpoint URL.

You can find these two keys from the Hasura project settings.

Next, you will need to pass the Hasura secret code through the header called “x-hasura-admin-secret”.

05. Moving through Queries.

Now that the basic structure is complete let’s move on to querying the GraphQL through URQL.

First, let’s consume the Query at the PokemonList.jsx file.

https://medium.com/media/1d12d7491fa7253e269426367abf6b2e/href

The above Query and Mutations are taken from the Hasura Dashboard. Hasura allows real-time subscriptions as well. So if you need to listen to the changes that occur to the Pokemons, you have to change the GraphQL Query from type Query to Subscription like below.

import { useSubscription } from 'urql';
const PokemonsSubscription = `
subscription PokemonsSubscription{
Pokemons_Pokemon {
id
name
power
description
}
}`;
const [res] = useSubscription({ query: PokemonsSubscription}, (messages = [], response) => {
return [response.PokemonsSubscription, ...messages];
});

Next, let’s move toward the pokemon creation in PokemonForm.jsx file.

https://medium.com/media/b2c39f83fa124a07543a0a119a077688/href

06. Creating Actions in Hasura

After that, we can start creating Actions. For this, we will be using the Pokemon API integration, which will be an external REST API.

Hasura’s actions will make a POST request, So to get the data from this endpoint, we will pass it through a Netlify function, creating a GET request to the Pokemon API.

You will have to create a Custom Query or a Mutation from the Hasura Dashboard to create this Action. Since we need to fetch data from the REST endpoint, let’s make a Query for this.

Here, the Action/Query will have a return object structure as mentioned below: Query and ResultOutput type.

type ResultOutput {
count: String!
next: String!
previous: String!
results: String!
}
type Query {
getPokemons: ResultOutput
}
Hasura Action getPokemon

This Action can be executed as a regular GraphQL query. So if we run the Query getPokemon, it will call the Netlify function, making a GET request to Pokemon REST API.

https://medium.com/media/064edb07dc7b0b569c80d871f350b7d0/href

07. Creating Events in Hasura

Hasura events allow you to fire a Serverless function or a REST call based on events that take place in your database. There a several types of Events in Hasura Events, They are.

  1. Event Triggers: These events are triggered when data changes take place in the database.
  2. Cron Triggers: These behave like Cron jobs (e.g., Database backup).
  3. One-off Scheduled Events: Timely scheduled trigger events.

The main events are the ones that will be triggered when you introduce changes to a table of your database. We will create another Netlify function that would save the data on AstraDB via the event trigger.

Serverless function details for the event

You can find the demo application for this example and the code in GitHub from this link.

Summary

Hasura is one of the best and easiest ways of implementing efficient and secure GraphQL endpoints. According to my experience, there are some key points why you should use Hasura with GraphQL,

  1. Hasura generates the schemas based on the relationships and data in your database tables.
  2. Hasura is open-source, so you are not vendor-locked, and you can host your server much more effortlessly.
  3. With some cool features like Actions and Events, Hasura is one of the services that deserve more attention in the GraphQL community.
  4. The simplicity of Haura also makes it a good option for beginners to get started with GraphQL.

One major downside of Hasura is that it doesn’t have any Identity Provider inbuilt. But you can integrate it with some 3rd part Authentication services like OAuth. Also, you can handle authorization easily with industry-standard methods like JWT tokens.

At last, do not forget to look at best practices when using GraphQL and Hasura.

Build & share independent JS components with Bit

Bit is an extensible tool that lets you create truly modular applications with independently authored, versioned, and maintained components.

Use it to build modular apps & design systems, author and deliver micro frontends, or simply share components between applications.

An independently source-controlled and shared “card” component (on the right, its dependency graph, auto-generated by Bit)

Bit: The platform for the modular web

Read More


Kickstart GraphQL Backends with Hasura was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Madushika Perera

A complete guide with the Developer’s perspective

GraphQL has become one of the popular alternatives for REST APIs. However, developing a GraphQL API from scratch has a steeper learning curve, along with the overheads of bootstrapping the project.

But what if there is a GraphQL API platform with a simplified programming model to kickstart?

This is where the savior Hasura comes into play.

So in this article, I will guide you through the path to develop an efficient GraphQL backend with Hasura.

What makes Hasura UNIQUE? ?

Hasura is an Open Source service that enables the frontends to access the data over a real-time GraphQL API.

The aim is to make life easier for developers and build applications faster. However, one of the common challenges for GraphQL is managing the database tables and the GraphQL schema mappings.

Hasura automates the management by pointing to your database and generating the GraphQL Schemas by going through the tables and relationships in your database.

You can even connect remote schemas (integrations) like Payment Gateways, making the Hasura service a single source of truth for your data.

Hasura also provides some unique features like

  • Actions: Actions allow you to add custom business logic to Hasura. Actions will enable you to create a Query or Mutation that you can execute to fire an action.
  • Events: Events allow you to trigger a REST endpoint call when some changes are introduced to your database (e.g., the Serverless function sends email). These events can be scheduled as well, like Corn jobs.

In addition,

  1. Hasura connects to your databases, REST endpoints, GraphQL endpoints, and 3rd party Services to a unified and real-time Grpahql API.
  2. Provides a cloud service that gives you a fully managed and production-ready GrpahQL API as a service.

Hasura has some powerful capabilities like Caching and Subscriptions for real-time data with faster load time.

Using it in Practice: Let’s Build an App

In this section, let’s see how we can build a GraphQL application using Hasura. This application will maintain a collection of Pokemons ?.

01. Create a project in the Hasura cloud.

Hasura Project

We will be using a Postgres Database for this demo application.

Hasura allows you to connect to your own Postgres DB or connect your Heroku account, creating a Postgres DB on Heroku.

In addition, Hasura provides a decent UI for database management.

Here you can make the schemas and table for your application.
Connecting Heroku and create Hasura

02. Moving into GraphQL playground.

Now that we have created our database on Heroku via Hasura. Let’s move towards the Hasura Dashboard, where you can find the GraphQL playground.

Here you can see that the schemas are automatically generated with the Queries and Mutation for the table you created in Postgres DB.

Hasura GraphQL Playground

In this application, we will be using several features provided by Hasura. They are Events and Actions, which will allow you to connect to external data sources or trigger events whenever some changes are introduced to your Postgres DB.

Demo application Architecture

As you can see in the above diagram, I’m using some External services like Pokemon API and Serverless functions (using Netlify f

unctions) for fetching and saving data.

03 Create the frontend application.

Now let’s create our frontend application which will consume the GraphQL endpoints in Hasura. We will be using create-react-app with URQL, which is a highly customizable and versatile GraphQL client.

Use the following command to create the React application.

npx create-react-app hasura-pokemon

04. Installing dependencies and connect the application.

Inside the project root, execute the following command.

yarn add urq graphql l@astrajs/collections antd node-fetch

This command will install the libraries for the URQL GraphQL client and some dependencies for our Netlify functions.

Now that the dependencies are installed, let’s connect to our Hasura GraphQL server. To do that, add the following code snippet inside the index.js file.

import { createClient, Provider } from 'urql';
const client = createClient({
url: process.env.REACT_APP_HASURA_URL,
fetchOptions: () => {
return {
headers: {
'content-type': 'application/json',
'x-hasura-admin-secret': process.env.REACT_APP_HASURA_SECRET
},
};
},
});
ReactDOM.render(
<Provider value={client}>
<App />
</Provider>,
document.getElementById('root')
);
Note that we have used some environmental variables to pass the Hasura Secret and Hasura GraphQL endpoint URL.

You can find these two keys from the Hasura project settings.

Next, you will need to pass the Hasura secret code through the header called “x-hasura-admin-secret”.

05. Moving through Queries.

Now that the basic structure is complete let’s move on to querying the GraphQL through URQL.

First, let’s consume the Query at the PokemonList.jsx file.

The above Query and Mutations are taken from the Hasura Dashboard. Hasura allows real-time subscriptions as well. So if you need to listen to the changes that occur to the Pokemons, you have to change the GraphQL Query from type Query to Subscription like below.

import { useSubscription } from 'urql';
const PokemonsSubscription = `
subscription PokemonsSubscription{
Pokemons_Pokemon {
id
name
power
description
}
}`;
const [res] = useSubscription({ query: PokemonsSubscription}, (messages = [], response) => {
return [response.PokemonsSubscription, ...messages];
});

Next, let’s move toward the pokemon creation in PokemonForm.jsx file.

06. Creating Actions in Hasura

After that, we can start creating Actions. For this, we will be using the Pokemon API integration, which will be an external REST API.

Hasura’s actions will make a POST request, So to get the data from this endpoint, we will pass it through a Netlify function, creating a GET request to the Pokemon API.

You will have to create a Custom Query or a Mutation from the Hasura Dashboard to create this Action. Since we need to fetch data from the REST endpoint, let’s make a Query for this.

Here, the Action/Query will have a return object structure as mentioned below: Query and ResultOutput type.

type ResultOutput {
count: String!
next: String!
previous: String!
results: String!
}
type Query {
getPokemons: ResultOutput
}
Hasura Action getPokemon

This Action can be executed as a regular GraphQL query. So if we run the Query getPokemon, it will call the Netlify function, making a GET request to Pokemon REST API.

07. Creating Events in Hasura

Hasura events allow you to fire a Serverless function or a REST call based on events that take place in your database. There a several types of Events in Hasura Events, They are.

  1. Event Triggers: These events are triggered when data changes take place in the database.
  2. Cron Triggers: These behave like Cron jobs (e.g., Database backup).
  3. One-off Scheduled Events: Timely scheduled trigger events.

The main events are the ones that will be triggered when you introduce changes to a table of your database. We will create another Netlify function that would save the data on AstraDB via the event trigger.

Serverless function details for the event
You can find the demo application for this example and the code in GitHub from this link.

Summary

Hasura is one of the best and easiest ways of implementing efficient and secure GraphQL endpoints. According to my experience, there are some key points why you should use Hasura with GraphQL,

  1. Hasura generates the schemas based on the relationships and data in your database tables.
  2. Hasura is open-source, so you are not vendor-locked, and you can host your server much more effortlessly.
  3. With some cool features like Actions and Events, Hasura is one of the services that deserve more attention in the GraphQL community.
  4. The simplicity of Haura also makes it a good option for beginners to get started with GraphQL.

One major downside of Hasura is that it doesn’t have any Identity Provider inbuilt. But you can integrate it with some 3rd part Authentication services like OAuth. Also, you can handle authorization easily with industry-standard methods like JWT tokens.

At last, do not forget to look at best practices when using GraphQL and Hasura.

Build & share independent JS components with Bit

Bit is an extensible tool that lets you create truly modular applications with independently authored, versioned, and maintained components.

Use it to build modular apps & design systems, author and deliver micro frontends, or simply share components between applications.

An independently source-controlled and shared “card” component (on the right, its dependency graph, auto-generated by Bit)

Bit: The platform for the modular web

Read More


Kickstart GraphQL Backends with Hasura was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Madushika Perera


Print Share Comment Cite Upload Translate Updates
APA

Madushika Perera | Sciencx (2021-07-15T15:16:30+00:00) Kickstart GraphQL Backends with Hasura. Retrieved from https://www.scien.cx/2021/07/15/kickstart-graphql-backends-with-hasura/

MLA
" » Kickstart GraphQL Backends with Hasura." Madushika Perera | Sciencx - Thursday July 15, 2021, https://www.scien.cx/2021/07/15/kickstart-graphql-backends-with-hasura/
HARVARD
Madushika Perera | Sciencx Thursday July 15, 2021 » Kickstart GraphQL Backends with Hasura., viewed ,<https://www.scien.cx/2021/07/15/kickstart-graphql-backends-with-hasura/>
VANCOUVER
Madushika Perera | Sciencx - » Kickstart GraphQL Backends with Hasura. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/07/15/kickstart-graphql-backends-with-hasura/
CHICAGO
" » Kickstart GraphQL Backends with Hasura." Madushika Perera | Sciencx - Accessed . https://www.scien.cx/2021/07/15/kickstart-graphql-backends-with-hasura/
IEEE
" » Kickstart GraphQL Backends with Hasura." Madushika Perera | Sciencx [Online]. Available: https://www.scien.cx/2021/07/15/kickstart-graphql-backends-with-hasura/. [Accessed: ]
rf:citation
» Kickstart GraphQL Backends with Hasura | Madushika Perera | Sciencx | https://www.scien.cx/2021/07/15/kickstart-graphql-backends-with-hasura/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.