Join any OpenAPI Swagger spec data to GraphQL using Hasura Remote Joins

TL;DR

Join any OpenAPI Swagger spec data to GraphQL using Hasura Remote Joins

Use Hasura Remote Joins to join data from your Postgres database with any OpenAPI/Swagger Spec GraphQL. Boilerplate – openapi-swagger-remote-schema

Join any OpenAPI Swagger spec data to GraphQL using Hasura Remote Joins

Remote Joins (available in preview) in Hasura allows you to join data across tables and remote data sources.

In this example, we will look at how data from a public API following the OpenAPI spec can be joined with existing data in Postgres using Hasura Remote Joins. We are going to make use of this OpenAPI Spec; it is a currency exchange rate API. Given a currency, it will return exchange rates for all other global currencies.

Alright, now let’s say there is a users table with columns id, name, currency.  Now we would like to query users data along with the exchange rate data in the public API. Let’s see how this can be done using the openapi-to-graphql tool.

Adding OpenAPI Spec as Remote Schema

To be able to query OpenAPI data via Hasura, it needs to be added as a Remote Schema using the Hasura Console.

Join any OpenAPI Swagger spec data to GraphQL using Hasura Remote Joins

Change the OpenAPI spec in the openapi.json file, as necessary for modifications. It currently uses this exchange-rate API.

Get the GraphQL API Endpoint from Glitch and add it as remote schema.

Join any OpenAPI Swagger spec data to GraphQL using Hasura Remote Joins

Deploy Custom Resolver

Now let’s add the Remote Relationship called currency_rates

Join any OpenAPI Swagger spec data to GraphQL using Hasura Remote Joins

Now the GraphQL query to fetch this data in a single API call would look like the following:

query {
  users {
    id
    name
    currency
    currency_rates {
      date
      rates
    }
  }
}

Notice that, the nested query currency_rates come from exchange rate API following the OpenAPI spec. It will apply the filter of users.currency = currency_rates.baseCurrency, there by only giving exchange rates related to the current user’s currency.

Checkout our other posts in the Remote Joins series:

Source: Hasura