Was this page helpful?

Using Contentful GraphQL with JavaScript

Disclaimer: GraphQL Content API is available on all spaces for customers on current pricing plans. If you are on a legacy plan, contact Customer Support to upgrade.

In order to pull content from the new Contentful GraphQL endpoint 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.

Log Request ID

When submitting support tickets, include the request ID along with other logs. Providing the request ID ensures faster and more effective responses to your inquiries. You can find it in the response header under x-contentful-request-id.

Get request ID from Apollo Client

Use the following code snippet to access response headers (request ID) from Apollo Client.

import {
    ApolloLink
} from 'apollo-link';
import {
    createHttpLink
} from 'apollo-link-http';

const httpLink = createHttpLink({
    uri: 'http://localhost:3001/graphql'
});

const afterwareLink = new ApolloLink((operation, forward) => {
    return forward(operation).map(response => {
        const context = operation.getContext();
        const {
            response: {
                headers
            }
        } = context;

        if (headers) {
            const requestId = headers.get("X-Contentful-Request-Id");

            if (requestId) {
                console.log("requestId", requestId);
            }

        }
        return response;
    });
});

// use with apollo-client
const link = afterwareLink.concat(httpLink);

Overview

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

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

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: