Was this page helpful?

Using Contentful GraphQL with JavaScript

In order to pull content from the new Contentful GraphQL endpoint (now in Beta) using JavaScript, you don’t require any additional tools or specific clients. You can execute queries to the GraphQL API over HTTP in the developer console of your browser, or using cURL, with the query as a hardcoded string. However, in many client-side applications, it is preferable to use a GraphQL client that provides caching, pre-fetching, and other advanced features. Apollo Client is one of the most popular and well supported GraphQL clients. It is being used by Contentful to create the GraphQL Example App in JavaScript. Apollo Client supports many platforms and the example app is built on React.

Overview

The workflow when working with the GraphQL API, Apollo Client, and a front-end JavaScript framework is as follows:

  • Write and test your queries using GraphiQL or your preferred GraphQL playground tool.
  • Integrate Apollo Client (and view-layer integrations) into your application.
  • Use queries from GraphiQL in your application; write logic for handling responses.
  • [Optional] Setup IntrospectionFragmentMatcher and replace ApolloBoost client with ApolloClient client.

Prerequisite

Before continuing with this guide, make sure you have a Contentful space and a CDA token. If you don’t have one, you can follow this Contentful + GraphQL quickstart guide to create and seed a space.

Write your GraphQL queries

Use a GraphQL playground, such as GraphiQL to test your GraphQL queries and get to know the schema. Contentful provides a GraphiQL interface to test queries in the browser at

https://graphql.contentful.com/content/v1/spaces/{SPACE_ID}/explore?access_token={CDA_TOKEN}

Integrate Apollo Client into your application

Follow the Apollo Client Getting Started Guide to install and integrate the client into your app. This guide is for React, but most of the steps are relevant for any frontend framework.

Use queries from GraphiQL in your application

Use your already-written queries and write code to handle responses.

import React from 'react'
import gql from 'graphql-tag'
import { Query } from 'react-apollo'
// You can import queries and fragments from a schema file
import { lessonFragment } from '../schema'
import { Loading, Error } from './LoadingStates'
import Course from './Course'

// You can also define queries directly in your React file
const courseFragment = gql`fragment CourseFragment on Course {
  slug
  title
  shortDescription
  description
  duration
  skillLevel
  lessonsCollection {
    items {
      ...LessonFragment
    }
  }
}
${lessonFragment}
`

const courseBySlug = gql`query CourseBySlug($slug: String!) {
  courseCollection(where: {slug: $slug}) {
    items {
      ...CourseFragment
    }
  }
}
${courseFragment}`

const CourseOverview = (props) => {
  const { 'course-slug': slug, 'lesson-slug': lessonSlug } = props
  return <Query query={courseBySlug} variables={{ slug }}>
    {
      ({ loading, error, data }) => {
        if (loading) return <Loading />
        if (error || data.courseCollection.items.length < 1) {
          return <Error />
        }
        const course = data.courseCollection.items[0]
        return (
          <Course course={course} lessonSlug={lessonSlug} />
        )
      }
    }
  </Query>
}

[Optional] Setup IntrospectionFragmentMatcher & replace ApolloBoost client with ApolloClient client

You may have encountered an error from Apollo Client if your client needs to use an IntrospectionFragmentMatcher instead of the default HeuristicFragmentMatcher. If you successfully executed your queries without seeing a related error, you can safely skip this step.

Depending on your content model and queries, you might need to configure Apollo Client to use an IntrospectionFragmentMatcher instead of the default HeuristicFragmentMatcher to match fragments in the cache.

If any of your content types have one-to-many relationships, the generated GraphQL schema represents these with Union types. If your queries use fragments on one of these union types, Apollo Client cache needs to know a bit more about your schema in order to properly match fragments. You can read more about GraphQL schema generation in the GraphQL API Reference here and more about fragment matching in the Apollo Docs here.

If you need to configure an IntrospectionFragmentMatcher, complete the following:

  1. Replace ApolloBoost client with ApolloClient client.

    • ApolloBoost is often recommended as the fastest way to setup an Apollo client. In order to setup the IntrospectionFragmentMatcher, you need to configure your client manually. First migrate from ApolloBoost to ApolloClient. Once this is completed, you can safely uninstall ApolloBoost from your project
  2. Introspect your schema and setup the IntrospectionFragmentMatcher

    • This requires writing a script to export parts of your schema as JSON and configuring your client to utilize it. Follow the guide here. To keep this exported schema up-to-date with your current content model, it’s recommended to include this script as part of your build process.

Additional Resources: