Build apps with rich content using Contentful and Hasura Remote Joins
Join application data in your database with content in Contentful with GraphQL and Hasura Remote Joins
Contentful is an API First CMS to build digital products. It offers a GraphQL API which can be joined with Hasura using Remote Schema.
Recently we launched Remote Joins feature (available in preview) which allows to join data across tables and remote data sources.
In this example, we will look at how a simple blog CMS in contentful can be joined with existing data in Hasura. For this example, the existing data in Hasura can just be users with their blog posts data coming from remote data source like Contentful. The same pattern of data coming from contentful can be used to build other apps with rich content, like for example a playlist app where video metadata come from contentful.
Alright, let's get started by creating the necessary content types in Contentful. Under Content model, create a new Content type for Blog Post and add the following fields -> title, content, created, cover_image, description, is_active, author. We will use the author field to connect this data with Hasura users table. Note that content field is of Rich text type and we will make use of it to create blog post content.
Adding Contentful as Remote Schema
To be able to query Contentful data via Hasura, it needs to be added as a Remote Schema using the Hasura Console.
- Get the GraphQL Content API Endpoint in the following format:
https://graphql.contentful.com/v1/spaces/<space-id>
And replace with the appropriate space id.
- In Contentful dashboard, click on Settings. Under Space Settings click on API keys. Copy the Space ID and paste in the above endpoint.
- Now copy Content Delivery API - access token and use it in Authorization headers like below:
Authorization: Bearer <access_token>
- In Hasura Console, head to Remote Schemas and enter GraphQL Server URL with the above contentful endpoint. Under Additional Headers, enter the Authorization header with the access_token as mentioned above.
Create Remote Relationship from Users to blogPostCollection type of Contentful.
Under configuration for blogPostCollection, we declare a where clause to say:
author: From column -> id
This ensures that while querying for blogs in users, we get only the relevant blogs written by the user who is queried for. Let's go ahead and create a row in users table and a simple blog post in Contentful.
This creates a new user with the id 1.
Under author, let's give the value 1, so that the data in Hasura is linked.
Now the GraphQL query to fetch this data in a single API call would look like the following:
query {
users {
id
name
blogs {
items {
title
content {
json
}
}
}
}
}
Notice that, the nested query blogs
come from Contentful and it will apply the filter of users.id = blogs.items.author, there by only giving blog posts written by the user.