AEM Server side Javascript to call third party API

Avatar

Avatar

Kam-nyc

Avatar

Kam-nyc

Kam-nyc

06-11-2020

Due to security and cross domain concerns, the AEM component has to call third party API using server side request.

So, client side "http get" to AEM sever, AEM server make request post to the third part API, once server side request successfully, it would pass the data back to client.

 

Do we have any examples about this either Java or Server side JavaScript would be helpful, thanks.

Accepted Solutions (1)

Accepted Solutions (1)

Avatar

Avatar

Manjunath_K

Avatar

Manjunath_K

Manjunath_K

06-11-2020

Hi @Kam-nyc ,

In backed you can call third party API as mentioned below, you can pass the response from API back to client side & use that response data as per your requirement.

 

MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); 
connectionManager.getParams().setConnectionTimeout(); //set this value
connectionManager.getParams().setSoTimeout(); //set this value
connectionManager.getParams().setMaxTotalConnections(); //set this value
connectionManager.getParams().setDefaultMaxConnectionsPerHost(); //set this value

HttpClient httpClient = new HttpClient(connectionManager);
PostMethod postMethod = new PostMethod("API endpoint");

try {
postMethod.setRequestEntity(new StringRequestEntity("data to send in request","contentType","charset")); //ex: new StringRequestEntity(inputData,"application/xml","UTF-8")
int statusCode = httpClient.executeMethod(postMethod);
if(statusCode == 200){
String responseData = postMethod.getResponseBodyAsString(); //send this responseData to front end
}
} catch (UnsupportedEncodingException exception) {
log.error("UnsupportedEncodingException occurred",exception);
} catch (IOException exception) {
log.error("IOException occurred",exception);
}

 

Hope this helps!

Answers (2)

Answers (2)

Avatar

Avatar

santhosh_kumark

Avatar

santhosh_kumark

santhosh_kumark

06-11-2020

Hi @Kam-nyc ,

 

You can try it using Java on backend to invoke the 3rd party - as shown here where we invoke a Google Service and display the results in front end component -- Creating an Adobe Experience Manager 6.3 HTL Component that displays data from a Restful Web Service

 

Hope this would be helpful.

 

Thanks & Regards,

Santosh

Avatar

Avatar

BrianKasingli

MVP

Avatar

BrianKasingli

MVP

BrianKasingli
MVP

08-11-2020

It's not a problem, you can make an HTTP request to an external micro-service securely via JavaScript without any problems. You just need to make sure your website's domain is whitelisted.

Here's an example using Javascript:

$("button").click(function(){
  $.post("https://api.adobe.com/profile",
  {
    name: "Bob",
    city: "Vancouver"
  },
  function(data, status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});