Expand my Community achievements bar.

SOLVED

graphQL: trying to find examples on how to implement graphQL + headless AEM if the data is coming from other APIs? (example: mulesoft)

Avatar

Level 9

I can only think of some sort of scheduled job (written in Java) that retrieves the data from the Mulesoft API and then creating CF/nodes from the response.

 

perhaps you have  some links/guides you can suggest? thank you.

1 Accepted Solution

Avatar

Correct answer by
Level 4

Hi @jayv25585659 ,

 

The 3rd answer by @aanchal-sikka  here may helps you.

View solution in original post

3 Replies

Avatar

Correct answer by
Level 4

Hi @jayv25585659 ,

 

The 3rd answer by @aanchal-sikka  here may helps you.

Avatar

Community Advisor

Hi @jayv25585659 ,

Integrating GraphQL with Headless AEM and external APIs like Mulesoft can be approached in multiple ways. Here’s a detailed guide on how you can achieve this:

Overview of the Approach

  1. Scheduled Job: Retrieve data from the Mulesoft API and store it in AEM as Content Fragments or nodes.
  2. GraphQL Queries: Use AEM’s GraphQL API to query the stored data.
  3. Frontend Integration: Fetch the data using GraphQL in your frontend application.

Steps to Implement

1. Scheduled Job to Fetch Data from Mulesoft

Create an OSGi service in AEM to run a scheduled job that fetches data from Mulesoft and stores it in AEM.

a. Add Dependencies: Ensure your pom.xml includes necessary dependencies for creating OSGi services and handling HTTP requests.

 

<dependency>
    <groupId>org.apache.sling</groupId>
    <artifactId>org.apache.sling.models.api</artifactId>
    <version>1.3.8</version>
</dependency>
<dependency>
    <groupId>org.apache.sling</groupId>
    <artifactId>org.apache.sling.commons.scheduler</artifactId>
    <version>2.7.0</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

 

b. Create the Scheduled Job:

 

package com.example.core.schedulers;

import org.apache.sling.commons.scheduler.ScheduleOptions;
import org.apache.sling.commons.scheduler.Scheduler;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component(immediate = true, service = Runnable.class)
public class MulesoftDataSyncScheduler implements Runnable {

    private static final Logger LOG = LoggerFactory.getLogger(MulesoftDataSyncScheduler.class);

    @Reference
    private Scheduler scheduler;

    @Activate
    protected void activate() {
        ScheduleOptions options = scheduler.EXPR("0 0 * * * ?"); // every hour
        scheduler.schedule(this, options);
    }

    @Override
    public void run() {
        LOG.info("Running scheduled job to fetch data from Mulesoft");
        // Fetch data from Mulesoft
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet request = new HttpGet("https://mulesoft-api-endpoint");
            HttpResponse response = httpClient.execute(request);
            String jsonResponse = EntityUtils.toString(response.getEntity());
            // Process and store the data in AEM
            storeDataInAEM(jsonResponse);
        } catch (IOException e) {
            LOG.error("Error fetching data from Mulesoft", e);
        }
    }

    private void storeDataInAEM(String jsonResponse) {
        // Implement logic to create/update Content Fragments or nodes in AEM
        // based on the fetched data
    }
}

 

2. Store Data in AEM

The storeDataInAEM method should parse the JSON response and create or update Content Fragments or nodes in AEM. Here's a basic example of how to create a node:

 

private void storeDataInAEM(String jsonResponse) {
    try (ResourceResolver resolver = resourceResolverFactory.getServiceResourceResolver(Map.of("service.user", "data-sync-service"))) {
        Session session = resolver.adaptTo(Session.class);
        Node rootNode = session.getNode("/content/data");
        
        // Parse the JSON response and iterate over the data
        JsonArray jsonArray = JsonParser.parseString(jsonResponse).getAsJsonArray();
        for (JsonElement element : jsonArray) {
            JsonObject jsonObject = element.getAsJsonObject();
            String nodeName = jsonObject.get("id").getAsString();
            Node dataNode = rootNode.hasNode(nodeName) ? rootNode.getNode(nodeName) : rootNode.addNode(nodeName);
            dataNode.setProperty("title", jsonObject.get("title").getAsString());
            dataNode.setProperty("description", jsonObject.get("description").getAsString());
            // Set other properties as needed
        }
        
        session.save();
    } catch (Exception e) {
        LOG.error("Error storing data in AEM", e);
    }
}

 

3. Query Data Using GraphQL

With the data stored in AEM as Content Fragments or nodes, you can leverage AEM’s GraphQL API to query the data.

a. Enable GraphQL: Ensure GraphQL is enabled in your AEM instance. You can enable GraphQL in the AEM Web Console.

b. Define GraphQL Schema: Create a schema for your Content Fragments or nodes.

c. Query the Data: Use the GraphQL API to query your data. Here’s an example query:

 

query {
  productList {
    items {
      title
      description
    }
  }
}

 

4. Frontend Integration

In your frontend application, use a GraphQL client (e.g., Apollo Client) to fetch the data from AEM’s GraphQL endpoint.

a. Install Apollo Client:

 

npm install @apollo/client graphql

 

b. Fetch Data:

 

import { ApolloClient, InMemoryCache, gql } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://your-aem-instance/graphql/endpoint',
  cache: new InMemoryCache()
});

client.query({
  query: gql`
    query {
      productList {
        items {
          title
          description
        }
      }
    }
  `
}).then(result => console.log(result));

 

  • Scheduled Job: Create a scheduled job in AEM to fetch data from Mulesoft and store it in AEM.
  • Store Data: Parse the API response and store it in AEM as Content Fragments or nodes.
  • GraphQL Query: Use AEM’s GraphQL API to query the stored data.
  • Frontend Integration: Fetch the data using a GraphQL client in your frontend application.

This approach ensures that your data remains in sync with the external API while leveraging AEM’s headless capabilities for efficient content delivery.

Avatar

Administrator

@jayv25585659 Did you find the suggestions from users helpful? Please let us know if you require more information. Otherwise, please mark the answer as correct for posterity. If you have found out solution yourself, please share it with the community.



Kautuk Sahni