How to call API after publishing content | Community
Skip to main content
Level 2
December 29, 2022
Solved

How to call API after publishing content

  • December 29, 2022
  • 1 reply
  • 700 views

Hi all,

 

I want to ask how to call an API every time when the users publish the content? 

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by Monendra_Singh

Hi @fang_29 

To call an API every time a user publishes content, you can create an OSGi event handler that listens for the com.day.cq.replication.ReplicationAction.EVENT_TOPIC event. This event is fired whenever content is replicated in AEM, which includes when content is published.

Here is sample code you can use and play around with:

 

@Component(service = EventHandler.class, property = { EventConstants.EVENT_TOPIC + "=" + ReplicationAction.EVENT_TOPIC }) public class MyEventHandler implements EventHandler { @Reference private SlingHttpService slingHttpService; @Override public void handleEvent(Event event) { // Check if the event is a publication event if (ReplicationAction.isPublicationEvent(event)) { // Get the path of the published content String path = ReplicationAction.getPath(event); // Call the API callAPI(path); } } private void callAPI(String path) { // Use the SlingHttpService to make a request to the API slingHttpService.doPost("/api/call", null, null, new HtmlResponse() { // Implement the onSuccess and onError methods to handle the API response }); } }

 

https://medium.com/@monendra80/3-ways-to-call-an-api-when-content-is-published-in-aem-b8cbb9b7e8da

 

Hope it helps.

Thanks,

Monendra

1 reply

Monendra_Singh
Monendra_SinghAccepted solution
Level 3
December 29, 2022

Hi @fang_29 

To call an API every time a user publishes content, you can create an OSGi event handler that listens for the com.day.cq.replication.ReplicationAction.EVENT_TOPIC event. This event is fired whenever content is replicated in AEM, which includes when content is published.

Here is sample code you can use and play around with:

 

@Component(service = EventHandler.class, property = { EventConstants.EVENT_TOPIC + "=" + ReplicationAction.EVENT_TOPIC }) public class MyEventHandler implements EventHandler { @Reference private SlingHttpService slingHttpService; @Override public void handleEvent(Event event) { // Check if the event is a publication event if (ReplicationAction.isPublicationEvent(event)) { // Get the path of the published content String path = ReplicationAction.getPath(event); // Call the API callAPI(path); } } private void callAPI(String path) { // Use the SlingHttpService to make a request to the API slingHttpService.doPost("/api/call", null, null, new HtmlResponse() { // Implement the onSuccess and onError methods to handle the API response }); } }

 

https://medium.com/@monendra80/3-ways-to-call-an-api-when-content-is-published-in-aem-b8cbb9b7e8da

 

Hope it helps.

Thanks,

Monendra