Expand my Community achievements bar.

SOLVED

Consume Api OSGI service

Avatar

Level 2

Hello, I need to consume APIs using AEM, I know it is possible to do it using OSGI service but I can't find any documentation or tutorial showing how to do it. The idea is to use the API through Java, and pass it through a varival to the ui.frontend. Today I use MapTo to do this communication, it works really well.

1 Accepted Solution

Avatar

Correct answer by
Level 8

Generally, we prefer to call the APIs from FE, you can use a Dispatcher proxy to do that. Refer to this URL to understand why AEM is not preferred to use as a proxy to make API calls. https://cqdump.joerghoh.de/2024/06/27/do-not-use-aem-as-a-proxy-for-backend-calls/. If you still need to use it for implementing some business logic refer to this URL -https://kiransg.com/2021/11/08/aem-rest-service-using-http-client-factory/ 

View solution in original post

6 Replies

Avatar

Community Advisor

Hi @ElvisRo ,

I am not sure why you have to call API thru java back-end, but by considering performance in mind, you should call the api from the front-end only. 
Normally we keep api endpoints and credentials in a form of OSGI configuration and read it from there and pass it to front-end for for further execution.

To Configure OSGI please see the video 

https://experienceleague.adobe.com/en/docs/experience-manager-learn/cloud-service/developing/basics/...
If you are using AEM as cloud service you can take help from Environment variable as well if it suites your requirement.

Hope this helps

Umesh Thakur

Avatar

Level 2

I intend to keep the call only on the Front-end, but I had already seen recommendations for OSGi.
So I won't get blocked by something from AEM if I do this on the front-end in ui.front-end, right?

Avatar

Community Advisor

You can make call from OSGI service that is totally fine but keep in mind, back-end call is expensive.

is it possible to share the recommendations or the exact meaning of OSGI, you are referring to?

Avatar

Correct answer by
Level 8

Generally, we prefer to call the APIs from FE, you can use a Dispatcher proxy to do that. Refer to this URL to understand why AEM is not preferred to use as a proxy to make API calls. https://cqdump.joerghoh.de/2024/06/27/do-not-use-aem-as-a-proxy-for-backend-calls/. If you still need to use it for implementing some business logic refer to this URL -https://kiransg.com/2021/11/08/aem-rest-service-using-http-client-factory/ 

Avatar

Administrator

@ElvisRo Did you find the suggestions helpful? Please let us know if you require more information. Otherwise, please mark the answer as correct for posterity. If you've discovered a solution yourself, we would appreciate it if you could share it with the community. Thank you!



Kautuk Sahni

Avatar

Level 2

package com.example.core.servlets;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.api.servlets.ServletResolverConstants;
import org.json.JSONArray;
import org.json.JSONObject;
import org.osgi.service.component.annotations.Component;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
* AEM Path-Based Servlet for User Notifications (Mock API for now).
*/
@component(
service = Servlet.class,
property = {
ServletResolverConstants.SLING_SERVLET_PATHS + "=/bin/user/notifications",
ServletResolverConstants.SLING_SERVLET_METHODS + "=GET",
ServletResolverConstants.SLING_SERVLET_METHODS + "=POST"
}
)
public class UserNotificationServlet extends SlingAllMethodsServlet {

private static final long serialVersionUID = 1L;

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");

// ===== MOCK RESPONSE =====
JSONArray notificationsArray = new JSONArray();

JSONObject notification1 = new JSONObject();
notification1.put("id", 101);
notification1.put("title", "New Feature Release");
notification1.put("message", "We have launched a new feature in the portal.");
notification1.put("date", "2025-04-03");

JSONObject notification2 = new JSONObject();
notification2.put("id", 102);
notification2.put("title", "System Maintenance");
notification2.put("message", "The system will undergo maintenance on Sunday.");
notification2.put("date", "2025-04-07");

notificationsArray.put(notification1);
notificationsArray.put(notification2);

response.getWriter().write(notificationsArray.toString(4)); // Pretty JSON Output

// ===== ACTUAL REST API CALL (Commented Out) =====
/*
try {
String apiUrl = "https://api.example.com/user/notifications"; // Replace with real API
String apiResponse = makeHttpRequest(apiUrl);
response.getWriter().write(apiResponse);
} catch (Exception e) {
response.getWriter().write("{\"error\": \"Failed to fetch notifications\"}");
}
*/
}

@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");

// ===== MOCK RESPONSE =====
JSONObject responseObject = new JSONObject();
responseObject.put("status", "success");
responseObject.put("message", "Notification sent successfully");
responseObject.put("notificationId", 2001); // Simulated ID

response.getWriter().write(responseObject.toString(4)); // Pretty JSON Output

// ===== ACTUAL REST API CALL (Commented Out) =====
/*
try {
String apiUrl = "https://api.example.com/user/notifications"; // Replace with real API
String requestData = "{\"title\": \"New Alert\", \"message\": \"Check your dashboard.\"}"; // Sample JSON
String apiResponse = makeHttpPostRequest(apiUrl, requestData);
response.getWriter().write(apiResponse);
} catch (Exception e) {
response.getWriter().write("{\"error\": \"Failed to send notification\"}");
}
*/
}

/**
* Makes an HTTP GET request to a given URL.
*/
private String makeHttpRequest(String apiUrl) throws IOException {
StringBuilder result = new StringBuilder();
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");

try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}
conn.disconnect();
return result.toString();
}

/**
* Makes an HTTP POST request to a given URL with JSON payload.
*/
private String makeHttpPostRequest(String apiUrl, String jsonData) throws IOException {
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);

conn.getOutputStream().write(jsonData.getBytes());

StringBuilder result = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}
conn.disconnect();
return result.toString();
}
}