-1

I am new to Salesforce and trying to learn calling external REST API from Apex class.

I have a simple spring boot rest api running on my localhost:8080.

API Endpoint : http://localhost:8080/api/message

Postman Screen Shot:

enter image description here

When I am trying to call it from Apex class, I am getting Access Denied and Status code is 403.

Salesforce Debug log: enter image description here

Apex Class Code:

public class ApexDemoApiConsume {

public String getMessage(){
    System.debug('Execution started !');
    String endPointURL = 'http://localhost:8080/api/message';
    Httprequest request = new HttpRequest();
    HttpResponse response = new HttpResponse();
    Http http = new Http();
    request.setHeader('content-type','application/Json');
    request.setMethod('GET');
    request.setEndpoint(endPointURL);
    try{
        response = http.send(request);
        System.debug('Response from the service'+response.getBody());
    }catch(Exception ex){
        System.debug('Exception occured '+ ex);
    }
    return response.getBody();
}

}

can someone help to identify what I am doing wrong.

1
  • 2
    Apex code runs on Salesforce servers and it does not access to your local machine. Oct 11 at 7:36
5

localhost means "the computer the program is running on." In Apex, this means you're trying to access the Salesforce server. Postman is running from your computer, so you can access servers running your own computer. Salesforce is not your computer, so you cannot access your server with localhost.

You will need to set up a public DNS with your public IP address, and use port forwarding or DMZ on your local network to expose the app. Even so, this may not work, as some IP addresses uses NAT to share public IP addresses with customers, so you might not be able to gain direct access to your server anyways. You might want to deploy your code to Heroku, Amazon EB, or some other server so you have public access to your server.

1
  • Thank you for the information. This really helps me. I am new and every bit of information helps me to gain more and more knowledge about Salesforce.
    – afulz29
    Oct 11 at 8:19
2

The Apex code is executing in a data centre out on the Internet but the URL you are supplying isn't accessible from there. Setup your test API on an Internet facing server (or use an existing REST service).

Postman is running inside your local network so can access http://localhost:8080.

1
  • Thank you for the information. This really helps me. I am new and every bit of information helps me to gain more and more knowledge about Salesforce.
    – afulz29
    Oct 11 at 8:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.