Explore GraphQL APIs

The GraphQL API of AEM provide a powerful query language to expose data of Content Fragments to downstream applications. Content Fragment models define the data schema that is used by Content Fragments. Whenever a Content Fragment Model is created or updated, the schema is translated and added to the “graph” that makes up the GraphQL API.

In this chapter, we will explore some common GraphQL queries to gather content using an IDE called GraphiQL. The GraphiQL IDE allows you to quickly test and refine the queries and data returned. GraphiQL also provides easy access to the documentation, making it easy to learn and understand what methods are available.

Prerequisites

This is a multi-part tutorial and it is assumed that the steps outlined in the Authoring Content Fragments have been completed.

Objectives

  • Learn to use the GraphiQL tool to construct a query using GraphQL syntax.
  • Learn how to query a list of Content Fragments and a single Content Fragment.
  • Learn how to filter and request specific data attributes.
  • Learn how to join a query of multiple Content Fragment models
  • Learn how to Persist GraphQL query.

Enable GraphQL Endpoint

A GraphQL endpoint is needed to be configured to enable GraphQL API queries for Content Fragments.

  1. From the AEM Start screen navigate to Tools > General > GraphQL.

    Navigate to GraphQL endpoint

  2. Tap Create in the upper-right-hand corner. In the dialog enter the following values:

    • Name*: My Project Endpoint.
    • Use GraphQL schema provided by … *: My Project

    Create GraphQL endpoint

    Tap Create to save the endpoint.

    GraphQL endpoints created based on a project configuration will only enable queries against models belonging to that project. In this case the only queries against the Person and Team models can be used.

    NOTE

    A Global endpoint can also be created to enable queries against models across multiple configurations. This should be used with caution as it may open the environment to additional security vulnerabilities, and add to overall complexity in managing AEM.

  3. You should now see one GraphQL endpoints enabled on your environment.

    Enabled graphql endpoints

Using the GraphiQL IDE

The GraphiQL Tool enables developers to create and test queries against content on the current AEM environment. The GraphiQL Tool also enables users to persist or save queries to be used by client applications in a production setting.

Next, explore the power of AEM’s GraphQL API using the built-in GraphiQL IDE.

  1. From the AEM Start screen navigate to Tools > General > GraphQL Query Editor.

    Navigate to the GraphiQL IDE

    NOTE

    For older versions of AEM the GraphiQL IDE may not be built in. It can be installed manually following these instructions.

  2. In the upper right-hand corner make sure the Endpoint is set to My Project Endpoint.

    Set GraphQL Endpoint

This will scope all queries to models created in the My Project project.

Query a list of Content Fragments

A common requirement will be to query for multiple Content Fragments.

  1. Paste the following query in the main panel (replacing the list of comments):

    query allTeams {
      teamList {
        items {
          _path
          title
        }
      }
    }
    
  2. Press the Play button in the top menu to execute the query. You should see the results of the content fragments from the previous chapter:

    Person List Results

  3. Position the cursor beneath the title text and enter CTRL+Space to trigger code hinting. Add shortname and description to the query.

    Update Query with code hiting

  4. Execute the query again by pressing the Play button and you should see the results include the additional properties of shortname and description.

    shortname and description results

    The shortname is a simple property and description is a multi-line text field and the GraphQL API allows us to choose a variety of formats for the results like html, markdown, json or plaintext.

Query for nested fragments

Next, experiment with querying is retrieving nested fragments, recall that the Team model references the Person model.

  1. Update the query to include the teamMembers property. Recall that this is a Fragment Reference field to the Person Model. Properties of the Person model can be returned:

    query allTeams {
        teamList {
            items {
                _path
                title
                shortName
                description {
                    plaintext
                }
                teamMembers {
                    fullName
                    occupation
                }
            }
        }
    }
    

    JSON Response:

    {
        "data": {
            "teamList": {
            "items": [
                {
                "_path": "/content/dam/my-project/en/team-alpha",
                "title": "Team Alpha",
                "shortName": "team-alpha",
                "description": {
                    "plaintext": "This is a description of Team Alpha!"
                },
                "teamMembers": [
                    {
                    "fullName": "John Doe",
                    "occupation": [
                        "Artist",
                        "Influencer"
                    ]
                    },
                    {
                    "fullName": "Alison Smith",
                    "occupation": [
                        "Photographer"
                    ]
                    }
                  ]
            }
            ]
            }
        }
    }
    

    The ability to query against nested fragments is a powerful of the AEM GraphQL API. In this simple example the nesting is only two levels deep. However its possible to nest fragments even further. For example if there was an Address model associated with a Person it would be possible to return data from all three models in a single query.

Filter a List of Content Fragments

Next, let’s look at how it is possible to filter the results to a subset of Content Fragments based on a property value.

  1. Enter the following query in the GraphiQL UI:

    query personByName($name:String!){
      personList(
        filter:{
          fullName:{
            _expressions:[{
              value:$name
              _operator:EQUALS
            }]
          }
        }
      ){
        items{
          _path
          fullName
          occupation
        }
      }
    }
    

    The above query performs a search against all Person fragments in the system. The added filter to the beginning of the query will perform a comparison on the name field and the variable string $name.

  2. In the Query Variables panel enter the following:

    {"name": "John Doe"}
    
  3. Execute the query, it is expected that only Persons will be returned with a value of “John Doe”.

    Use Query Variables to filter

    There are many other options for filtering and creating complex queries, see Learning to use GraphQL with AEM - Sample Content and Queries.

  4. Enhance above query to fetch profile picture

    query personByName($name:String!){
      personList(
        filter:{
          fullName:{
            _expressions:[{
              value:$name
              _operator:EQUALS
            }]
          }
        }
      ){
        items{
          _path
          fullName
          occupation
          profilePicture{
            ... on ImageRef{
              _path
              _authorUrl
              _publishUrl
              height
              width
    
            }
          }
        }
      }
    }
    

    The profilePicture is a content reference and it is expected to be an image, therefore built-in ImageRef object is used. This allows us to request additional data about the image being reference, like the width and height.

Query a single Content Fragment

It is also possible to directly query a single Content Fragment. Content in AEM is stored in a hierarchical manner and the unique identifier for a fragment is based on the fragment’s path.

  1. Enter the following query in the GraphiQL editor:

    query personByPath($path: String!) {
        personByPath(_path: $path) {
            item {
            fullName
            occupation
            }
        }
    }
    
  2. Enter the following for the Query Variables:

    {"path": "/content/dam/my-project/en/alison-smith"}
    
  3. Execute the query and observe that the single result is returned.

Persist Queries

Once a developer is happy with the query and data returned, the next step is to store or persist the query to AEM. Persisted queries is the preferred mechanism for exposing the GraphQL API to client applications. Once a query has been persisted, it can be requested using a GET request and cached at the Dispatcher and CDN layers. The performance of persisted queries is much better. In addition to performance benefits, persisted queries ensure that extra data is not accidentally exposed to client applications. More details about Persited queries can be found here.

Next, persist two simple queries, they will be used in the next chapter.

  1. In the GraphiQL IDE enter the following query:

    query allTeams {
        teamList {
            items {
                _path
                title
                shortName
                description {
                    plaintext
                }
                teamMembers {
                    fullName
                    occupation
                }
            }
        }
    }
    

    Verify that the query works.

  2. Next tap Save As and enter all-teams as the Query Name.

    The query should now be shown under Persisted Queries in the left rail.

    All Teams Persisted Query

  3. Next tap the elippses next to the persistent query and tap Copy URL to copy the path to your clipboard.

    Copy Persistent Query URL

  4. Open a new tab and paste the copied path in your browser:

    https://$YOUR-AEMasCS-INSTANCEID$.adobeaemcloud.com/graphql/execute.json/my-project/all-teams
    

    It should look similar to the above path. You should see the JSON results of the query returned.

    Breaking the URL down:

    Name Description
    /graphql/execute.json Persistent query endpoint
    /my-project Project configuration for /conf/my-project
    /all-teams Name of the peristent query
  5. Return to the GraphiQL IDE and use the plus button + to perist the NEW query

    query personByName($name: String!) {
      personList(
        filter: {
          fullName:{
            _expressions: [{
              value: $name
              _operator:EQUALS
            }]
          }
        }){
        items {
          _path
          fullName
          occupation
          biographyText {
            json
          }
          profilePicture {
            ... on ImageRef {
              _path
              _authorUrl
              _publishUrl
              width
              height
            }
          }
        }
      }
    }
    
  6. Save the query as: person-by-name.

  7. You should have 2 persisted queries saved:

    Final persisted queries

Publish GraphQL Endpoint & Persisted Queries

Upon review and verification, publish the GraphQL Endpoint & Persisted Queries

  1. From the AEM Start screen navigate to Tools > General > GraphQL.

  2. Tap the checkbox next to My Project Endpoint and tap Publish

    Publish GraphQL Endpoint

  3. From the AEM Start screen navigate to Tools > General > GraphQL Query Editor

  4. Tap the all-teams from Persisted Queries panel and tap Publish

    Publish Persisted Queries

  5. Repeat above step for person-by-name query

Solution Files

Download the content, models, and persitent queries created in the last three chapters: tutorial-solution-content.zip

Additional Resources

For many more examples of GraphQL queries see: Learning to use GraphQL with AEM - Sample Content and Queries.

Congratulations!

Congratulations, you just created and executed several GraphQL queries!

Next Steps

In the next chapter, Build React app, you will explore how an external application can query AEM’s GraphQL endpoints and leverage these two persisted queries. You will also be introduced to some basic error handling.

Install the GraphiQL Tool (Optional)

For some versions of AEM the GraphiQL IDE tool needs to be manually installed. Follow the instructions below to manually install:

  1. Navigate to the Software Distribution Portal > AEM as a Cloud Service.

  2. Search for “GraphiQL” (be sure to include the i in GraphiQL.

  3. Download the latest GraphiQL Content Package v.x.x.x

    Download GraphiQL Package

    The zip file is an AEM package that can be installed directly.

  4. From the AEM Start menu navigate to Tools > Deployment > Packages.

  5. Click Upload Package and choose the package downloaded in the prior step. Click Install to install the package.

    Install GraphiQL Package

On this page