Introduction to Hasura GraphQL Engine for Dynamic APIs with PostgreSQL

Generally, over the past years, REST APIs have undergone criticism as inflexible whilst dealing with rapidly changing tech requirements. In retrospect, many believe GraphQL was created to cope with this need for additional flexibility and efficiency in API development. Thus, mitigating the deficiencies of REST APIs. A result of Facebook’s transition away from HTML5 applications to more robust and native set-ups, GraphQL has risen in popularity and adoption over the past five years with good reason. In this blog, we shall delve into the GraphQL phenomenon, PostgreSQL and later have a thorough introduction to Hasura GraphQL engine. In a snippet, the Hasura GraphQL engine-PostgreSQL relationship and eco-system.

GraphQL: A Facebook Rebellion

While many believe that GraphQL was created as a rebellion to REST APIs, this could be further from the truth. Ironically, it was created to simply serve an internal need at Facebook. Originally engineered and open-sourced by the Facebook Team, GraphQL is often confused as a database technology. Essentially, despite the misconception, GraphQL is technically a query language for APIs and not databases. Consequently, it reduces the complexity of building APIs, abstracting all requests to a single endpoint. Unlike traditional REST APIs, GraphQL is declarative, meaning whatever is requested is returned. Though to get a little more context, we’ll need to take a step back and revisit REST APIs.

The REST Architecture

Typically, APIs are rules,routines or protocols that specify how software components should interact. The Representational State Transfer (REST) is basically an API design architecture normally leveraged in implementation of web services where everything is considered a ‘resource’. Unfortunately, the RESTful methodology was consistently limited to dealing with single resources. Hence, if data was needed and coming from two or more resources, for instance, posts and users, multi-round trips to the server would be required to collect everything needed. Additionally, REST faced issues with ‘over’ and ‘under’ fetching. All of this wasn’t ideal, especially with the emergence of more data-driven apps handling large datasets combining related resources. Which could explain the predicament Facebook faced.

Thus, the need for an API architecture that would take a more flexible and progressive approach.

The Creation of an Alternative

Alternatively, GraphQL doesn’t think of data in terms of resource URLs, secondary keys, or tables but in terms of a graph of objects and the models utilising NSObjects or JSON. Specifically, GraphQL doesn’t need dedicated endpoints per use case as different capabilities and use cases can be represented in a single “Graph”. Using the GraphQL query language, you can describe exactly what the response should look like hence no additional server round trips needed. As an application layer query language, it’s designed to interpret a string from a server/client and return that data in a stable, understandable and predictable format. It’s simply a tool to better consolidate data.

Simplicity, Stability and Efficiency.

Truth is that not all projects require GraphQL despite its well-defined schema, so we know for sure we won’t over-fetch. Though, if we have an enterprise product that relies on data from multiple sources, for instance MySQL, Postgres, and other APIs, then GraphQL is the better option. GraphQL prides itself on simplicity especially concerning data retrieval since data is collected under a common endpoint or call. Essentially, since clients get what they exactly need, this effectively reduces the size of each request made by the client resulting in high-performance applications. Since GraphQL unifies data that would otherwise require multiple endpoints, it eases complex repeat retrievals, thus better query efficiency. Consequently, with its simplicity comes more back-end stability, planning, construction, execution, and continued operation over time.

Advantages of GraphQL

In a nutshell, GraphQL allows extraction of data with easily understandable queries, allows speedy development of lightweight and fast applications because data is accessed more directly instead of through a server. Furthermore, it allows the retrieval of several resources with one query without using several URLs or chaining of resources, whilst using one endpoint for all data. Remember, data is defined on the server with a graph-based scheme, so is delivered as a package rather than through multiple calls. This allows an operational boost in aggregating API responses during API development.

This, in turn, lessens the load on front end development teams, facilitates API versioning, simplifies maintenance, and saves up on data transfer demands. Furthermore, it allows for more predictability when receiving data, supports declarative data fetching and mitigates over-fetching and under-fetching. Essentially, over-fetching occurs when a client downloads more information than is actually required in the app while under-fetching implies that a specific endpoint hasn’t provided enough of information thus requiring the client to make additional requests to fetch what it needs. 

Technically, GraphQL is a wrapper that can be defined meaning you don’t have to fully replace a REST system. Essentially, this means that GraphQL is compatible with systems that REST-centric APIs are compatible with. Additionally, GraphQL allows seamless and independent development of front and back-end. This is because once the schema is well defined, teams working on front-end and back-end are both aware of the definite structure of the data. All of these benefits are seen as advantageous by many full-stack engineers. Lastly, GraphQL has an amazing capacity for thorough introspection and self-documentation.

GraphQL Use Cases in API development

Considered extremely powerful, GraphQL is used by Full-stack developers seeking stable readability with quick speed and indexing. Specifically, GraphQL is useful in API development that requires high data throughput. As a matter of fact, it minimizes the amount of data required for transfer over a network. This is highly beneficial for mobile users, low-powered devices and sloppy networks. Which is amongst the initial reasons Facebook engineered GraphQL. Contrary to belief, GraphQL isn’t only applicable in huge complex databases, it can create relatively simple databases with greater efficiency.

Additionally, it can be applied on a variety of unique front-end frameworks and platforms, providing a heterogeneous landscape maintained with one API to fit all user requirements. Furthermore, it facilitates rapid feature development as it dramatically increases the feature velocity for full-stack developer teams. It does this by reducing the communication required between teams while developing new features as front-end developers can make API requests, for instance, to introduce new features or change existing ones without having to wait for back-end developers to deliver. This quick GraphQL summary should be sufficient for now as we get into our introduction to Hasura GraphQL engine. Though let’s touch PostgreSQL for a bit more context.

What is PostgreSQL?

As a free community-driven relational database management system, PostgreSQL is not owned by any single company. Considered the most powerful, internally consistent RDBMS available, Postgres was written in C, and supports a number of programming languages, such as C/C++, JavaScript, Java, Python, R, Go, Lisp, .Net etc. Increasingly preferred amongst most full-stack developers, PostgreSQL is more feature-rich than its sister MySQL, gaining popularity because of its features, scalability and performance. PostgreSQL is popular in projects where requirements revolve around complex procedures, intricate designs, bespoke integration, and data integrity.

Advantages of Postgres for Full-Stack developers

Generally, features such as full-text search, JSON columns, logical replication, give Postgres the upper hand on MySQL. This is optimal for the performance demands of typical commercial databases while allowing consolidation of several database systems into one for less overhead and cost. Furthermore, its more recent features for Key-Value-Storage (JSON / JSONB column types) make it a suitable alternative to NoSQL-databases. Additionally, it supports clustering or a master-slave-architecture, making it well-suited for cloud-like environments. In addition, its popular foreign-data-wrapper extension allows the querying of external sources directly from within PostgreSQL when necessary. Specifically, it’s best suited for systems requiring execution of complex queries, data warehousing and dynamic data analysis.

As a matter of fact, PostgreSQL better supports certain features that MySQL does not. For instance, check constraints, rich data types (such as arrays, maps, JSON), richer geospatial Support (PostGIS), and richer full-text support. Additionally, it supports non-blocking index creation, partial Indexes, common table Expressions and more dynamic analytics functions. Notwithstanding, PostgreSQL offers native SLL support for connections for the encryption of client/server communications, as well as a built-in enhancement named SE-PostgreSQL which provides additional access controls based on SELinux policy.

With many rich features for enterprise-grade products, PostgreSQL is appropriate for large systems where data requires authentication and read/write speeds are critical to project success. Furthermore, it also supports multiple performance enhancers that are normally available in proprietary solutions.  Such include: concurrency without read locks, SQL server, and Geospatial data support to mention a few.

Another main advantage of the Postgres architecture is its unique extensibility. It allows users to add features such as data types, index access methods, server programming languages, foreign data wrappers (FDW) and loadable extensions without changing the core system code. It leverages a modern multi-core processor architecture thus allows its performance to grow almost linearly as the number of cores increases. This is importantGenerally, features such as full-text search, JSON columns, logical replication, give Postgres the upper hand on MySQL. This is optimal for the performance demands of typical commercial databases while allowing consolidation of several database systems into one for less overhead and cost. Furthermore, its more recent features for Key-Value-Storage (JSON / JSONB column types) make it a suitable alternative to NoSQL-databases. Additionally, it supports clustering or a master-slave-architecture, making it well-suited for cloud-like environments. In addition, its popular foreign-data-wrapper extension allows the querying of external sources directly from within PostgreSQL when necessary. Specifically, it’s best suited for systems requiring execution of complex queries, data warehousing and dynamic data analysis.

Cons of PostgreSQL

Generally, if you fancy ANSI SQL standards, do consider PostgreSQL, though if you prefer ODBC standards, then opt for MySQL. Unfortunately, Postgres occasionally falls short in performance with live, “always up” production environments. An additional disadvantage with Postgres is the fact that its replication is implemented at the storage engine level. This makes it more expensive than MySQL’s replication, which is more mature and implemented at the “query engine level”.

Introduction to Hasura GraphQL engine

Since we have briefly covered GraphQL API development and PostgreSQL, we should have enough context for an introduction to Hasura GraphQL engine. Basically, Hasura is simply a GraphQL engine for the PostgreSQL RDBMS, providing a simplified way of bootstrapping and managing GraphQL API development. In retrospect, Hasura is currently the only readily available solution that instantly adds GraphQL-as-a-Service onto existing PostgreSQL based applications. Essentially, bypassing the time-consuming task of writing backend code that processes GraphQL.

Hasura Simplified

Let’s take a minute to simplify Hasura further. Basically, APIs are interfaces that allow you to request information (a query), and thus respond by sending JSON or XML data. That database is normally hosted and fetched from a server. This is where Hasura comes in to simplify things. In hindsight, Hasura GraphQL engine is a server that handles your GraphQL queries over a Postgres database. This effectively reduces the time it takes your app to be production ready allowing you to create, view and modify tables of your database with ease in just a few clicks. Consequently, this allows full-stack developers to build scalable GraphQL applications on PostgreSQL within a shorter time. This saves developers weeks of upfront coding and can prevent problematic data-leaking bugs from making it to production.

What problem is Hasura solving in API development?

Generally, Hasura simplifies API lifecycle management during large-scale production use especially for complex APIs. Above all, the GraphQL Engine attracts full-stack developers who are backlogged with enterprise API development projects utilising existing PostgreSQL databases. Ideally, since GraphQL allows for lightning-fast API development cycles, Hasura provides a simplified way for organizations to incrementally move to GraphQL, without affecting existing applications, databases or users. Besides its lightweight and high performance, the engine comes with an admin UI, allowing you to explore your GraphQL APIs and manage your database schema and data visually.

Advantages of Hasura

Firstly, Hasura has a solid, stable model for managing database changes or “migrations”. This is advantageous since database schema management is often tricky. For instance, tasks such as; tracking of changes over time and associating schema changes with API enhancements (schema management). Furthermore, routine jobs like maintaining scripts that can deploy a fresh database or roll back changes can prove tedious and cause hard-to-diagnose bugs or an outage.  As a positive side note, Hasura database migration components are plain SQL, hence portable outside the Hasura toolset. All in all, Hasura has great schema management features and you need not write code to handle web socket connections.

Secondly, Hasura GraphQL engine makes it easy to fetch required data with a single query. It does this by allow you to add views as relationships to tables or other views. Additionally, it allows writing of custom resolvers with schema-stitching and integration of serverless functions or microservice APIs that get triggered on database events. This can come in handy and facilitates building of 3factor apps. As a matter of fact, Hasura is an extremely lightweight engine. In retrospect, it consumes only up to 50MB of RAM even while serving more than 1000 requests/per second. A brilliant return on investment!

Specifically, Hasura further facilitates fine-grained API data-level authorization and authentication well. It allows connection to a preferred authentication provider either via webhook, JWT, Auth0 or custom implementations. And thus, specification of roles for users, defining who can access different data, for instance, admin, anonymous users, etc. Generally, its granular access control system is based on the database table structure similar to the GraphQL schema. Additionally, custom permission rules are strictly defined based on database operations and values.

Lastly, Hasura brilliantly supports efficient paging with a simple SQL-like offset/limit model. For instance, it uses the access control model to restrict the number of rows returned for a given query. Its model allows tuning of limits by role. For example, users that impose a much higher request rate are limited to smaller row limits. This avoids stressing the database and GraphQL engine. Additionally, notably, Hasura doesn’t restrict you to GraphQL only. You can still run REST or other non-GraphQL micro services against the Postgres tables that Hasura manages. This is possible with Hasura’s automatic schema stitching. This allows the merging of a non-Hasura GraphQL service and back-end for a single unified schema, combining new, Hasura-managed APIs with legacy APIs and data.

Hasura Use Cases

Suitable for high-performance environments, the Hasura Engine offers speed whilst automating GraphQL-Postgres implementation on existing databases. Consequently, this provides companies already using Postgres a less stressful and incremental way of moving over to GraphQL by linking existing tables into a “graph”. Hasura efficiently takes care of the schema stitching allowing you to easily apply custom business logic. With Remote GraphQL schemas, Hasura can be leveraged as a gateway for custom business logic allowing you to write to GraphQL servers in your favourite language, then later expose the data to a single endpoint. Furthermore, Hasura has great syntax for queries and mutations with built-in live-queries called subscriptions in GraphQL.

The few Hasura Limitations

Unfortunately, Hasura’s access control system model won’t fully work for every application. For instance, it doesn’t fully support API access authorization at the level of individual input parameters. Not to mention the fact that it’s restricted to the Postgres database requiring migration in most cases. Though negligible, the error messages the GraphQL API returns for malformed requests are quite unfriendly on Hasura. Otherwise, there is little that Hasura cannot do as we have seen in this introduction to Hasura GraphQL Engine.

Conclusion

In conclusion, as GraphQL grows, it will quintessentially further simplify API development within enterprises to build at web-scale. With the wide-scale rapid adoption of GraphQL across a diverse set of industries, Hasura has the potential to further automate the creation and management of APIs with industry-standard technologies of choice, GraphQL and Postgres. Hasura simplifies creation of CRUD(Create, read, update and delete) GraphQL backends. More importantly, Hasura is by far the best and only option if you’re starting from scratch with a GraphQL-centric API and Postgres, without writing backend code. For any queries or consultations on GraphQL and Hasura enterprise possibilities, do feel free to reach out to us. That’s it for our introduction to Hasura GraphQL Engine.

Bhargav Bhanderi

Bhargav Bhanderi

Sr. Php Developer

Head of Sales at Creole Studios and veteran web programmer who looks like a dragon warrior but is in fact Master Shifu.