Understanding Content Fragment and GraphQL Jargons


In this blog, we will discuss the terminologies associated with Headless implementation through the use of Content Fragments and GraphQL.

Prerequisites:

All the examples provided in this blog are sourced from Adobe’s WKND Shared repository. Alternatively, you can opt to install the WKND Sites project, which includes the WKND Shared components. By installing WKND Shared, you’ll gain access to demo content fragments, a GraphQL endpoint, and sample persisted queries.

Key terminologies

Lets begin by understanding the key terms you’ll encounter along the journey of implementing headless with Content Fragment and GraphQL:

1. Content Fragment Models (CFM):

Content Fragment Models serve as templates that establish the structure and characteristics of your content. These models define the fields and their associated data types. For instance, you would define separate CFM for “Article” or “Author”, since they define 2 different entities with different properties

Example: Here is a “Author” Content Fragment Model available in WKND-Shared samples

2. Content Fragments (CF):

These are individual, modular pieces of content that you can create and manage within AEM. CFM are templates used to create these Content Fragments. All the fields you configure in the CFM are accessible for authoring within the Content Fragment itself, similar to how pages are authored based on templates in a traditional headful approach.

One of the key advantages of Content Fragments is that they are presentation-agnostic and structured. This means they can be used consistently across various channels and devices without being tied to a specific layout or format.

To illustrate, here is a Content Fragment containing information about the author of an article. This Content Fragment serves as a single, reusable data module within the entire system. Its purpose is to consistently display author information, regardless of the channel or device used for content delivery.

3. GraphQL Schema and Content Fragment Models:

A GraphQL Schema is similar to a database, which has structure and data types available for querying data through a GraphQL API (GraphQL API is a query language).

Each Content Fragment Model in AEM corresponds to a specific GraphQL Schema. GraphQL Schema generation is dynamic, adapting to changes in Content Fragment Models. Any changes made to a CFM, created, modified, or deleted, the GraphQL Schema is automatically updated to reflect these changes. This dynamic approach ensures flexibility and adaptability.

In essence,

  • Content Fragment Models act as the building blocks for creating structured content
  • While GraphQL Schema serves as a guide for how that content can be interacted with and queried via a GraphQL API.

4. GraphQL Queries

GraphQL queries are requests made by a client to fetch specific data in a structured and efficient manner. GraphQL queries are flexible and allow clients to specify exactly what data they need, which fields they want to retrieve, and how the data should be structured in the response.

When applied within AEM, the GraphQL API enables the streamlined delivery of Content Fragments to JavaScript clients in headless CMS implementations.

Basic structure of GraphQL queries:

The general structure of a GraphQL query consists of the following components:

1. Operation Type: GraphQL supports two main types of operations: `query` for fetching data and `mutation` for modifying data. The operation type is specified at the beginning of the query.

query {
     // Your query fields go here
}

2. Root Field: The root field is the entry point for the query and represents the data you want to retrieve. It is followed by a set of curly braces `{}`.

query {
  articleList {             //Root Field
    items {
      title
      slug
    }
  }
}

3. Selection Set: Within the curly braces, you specify the fields you want to retrieve for the root field. These fields can be nested, allowing you to fetch related data.

query {
  articleList{
    items {
      title             //Selection Set
      slug              //Selection Set
      authorFragment {
        firstName       //Selection Set
        lastName        //Selection Set
      }
    }
  }
}

4. Arguments: You can provide arguments to the fields to filter, paginate, or customize the data you receive. Arguments are specified within parentheses `()` after the field name.

query {
articleList(_locale: "fr") {
items {
title
slug
authorFragment {
firstName
lastName
}
}
}
}

5. Variables: Variables are used to parameterize the query, allowing you to pass dynamic values into the query at runtime. They are preceded by the `$` symbol and are defined in the query operation.

query getArticleBySlug($slug: String!) {
  articleList(
    filter: {slug: {_expressions: [{value: $slug}]}}
    ) {
    items {
      _path
      title
      slug
    }
  }
}

For sample queries from Adobe, visit Sample GraphQL queries,

5. GraphQL Endpoints:

In AEM, GraphQL functionality is accessed through specific endpoints. Two main types of endpoints exist:

5.1 Global Endpoint:

  • Available for use across all sites within the AEM instance.
  • It can harness Content Fragment Models (CFMs) from all Sites configurations.
  • Shared CFMs among different Sites configurations should be created under the global Sites configurations.
  • The repository path for the GraphQL global endpoint is: /content/cq:graphql/global/endpoint

Site Specific Endpoint:

  • Tailored for a specific site or project within the AEM instance.
  • Utilizes CFMs from the designated Sites configuration, along with those from the global Sites configuration.
  • The repository path for the GraphQL global endpoint is: /content/cq:graphql/<site-name>/endpoint
  • Persisted Queries (PQ) are tenant-specific, meaning that PQs saved within one tenant cannot be accessed or utilized by other tenants. PQs remain isolated within their respective tenants.

6. Persisted Queries:

It is a mechanism where GraphQL queries are saved and assigned unique identifiers on the server side. Instead of sending the entire GraphQL query in the request, clients can send the query’s identifier, and the server retrieves and executes the corresponding query associated with that identifier.

Persisted Queries Location: In AEM, persisted GraphQL queries are stored in a specific location in the content repository. This location follows the format /conf/<site-name>/settings/graphql/persistedQueries, where <site-name> represents the name of the AEM site or project.

GraphQL Data Access: Authentication with Access Tokens and Credentials

To access data through GraphQL, it’s necessary to provide authentication details via credentials or access token. For details , please refer to link

Lets create and execute GraphQL queries now:

6.1 Create query:

Two approaches are available for generating GraphQL queries:

Approach-1: Manual Query Submission

Clients manually send GraphQL queries to the server using PUT requests. Queries are sent to the server via the /graphql/persist.json/<site-name>/<persisted-label> endpoint.

This approach is suitable for ad-hoc queries and developers familiar with GraphQL query construction.

curl -H "Authorization: Bearer <access_token>" -X  PUT \
    -H "Content-Type: application/json" \
    "http://localhost:4502/graphql/persist.json/wknd/plain-article-query" \
    -d \
'{
  articleList {
    items{
        _path
        author
        main {

            json
        }
    }
  }
}
  • Modify: Use POST request to modify an existing query
  • List: Retrieve the list of persisted queries by using the /graphql/list.json endpoint.
  • Delete: To remove an existing query, initiate a DELETE request to the /graphql/persist.json/<site-name>/<persisted-label>.
curl -H "Authorization: Bearer <access_token>" -X DELETE   http://localhost:4502/graphql/persist.json/<site-name>/<persisted-label>.

Approach-2: GraphiQL Explorer Tool

The GraphiQL Explorer tool simplifies query creation, testing, and persistence. Developers can create queries using an interactive and user-friendly interface.

Queries can be executed against the AEM environment for real-time feedback. Queries can be saved and reused, making it ideal for production applications.

This approach enhances query management and is user-friendly.

6.2 Server-side Retrieval: To retrieve and execute a persisted GraphQL query, developers use the URL endpoint /graphql/execute.json/<site-name>/<persisted-label>. This endpoint allows them to fetch the previously saved query and execute it to obtain data from the AEM system.

curl -H "Authorization: Bearer <access_token>" -X GET http://localhost:4502/graphql/execute.json/<site-name>/<persisted-label>

Advantages of using Persisted queries

  • Efficiency: The size of the request is reduced because the query text is no longer transmitted with every request. This can lead to significant savings in bandwidth and faster response times.
  • Security: It can enhance security by limiting exposure to query text, which might contain sensitive information or be exploited for attacks.
  • Caching: The response of a GET request can be cached at the dispatcher and CDN layers, ultimately improving the performance of the requesting client application
  • Predictability: It provides predictable query execution, as the server ensures that only valid, predefined queries are executed. For Content Fragments and GraphQL, Persisted Queries can be particularly useful in scenarios where you have a set of commonly used queries that don’t change frequently. This mechanism can help optimize and secure the interaction between clients and the GraphQL server when working with Content Fragments.

For more details about persisted queries and caching strategies, please refer to link

It’s time to get some hands-on!

For practical experience, you can refer to the following Adobe resources:

References

One thought on “Understanding Content Fragment and GraphQL Jargons

Leave a comment