1

I am trying to make a callout to an open public api. When I tested it on Postman, it is giving me the expected response. But when I tried it on the Apex class, the response is giving me the following output.

enter image description here

I have configured 'the remote site settings' for the endpoint. Anyone knows what can be the problem?

Here is my code:

    public class retrieveStocks {       
       public static HttpResponse retrieveStocks() {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://tradestie.com/api/v1/apps/reddit');
        request.setHeader('Content-Type', 'application/json');
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        // If the request is successful, parse the JSON response.
        if(response.getStatusCode() == 200) {
            // Deserializes the JSON string into collections of primitive data types.
            system.debug(response.getBody());
        }
        system.debug(response.getBody());
        return response;
    }
}

As always, thank you in advance!!!!!

2 Answers 2

3

This happens because Postman automatically redirects requests that return a 3xx response.

Disable the automatic redirection for 3xx responses. To do this, open the Settings tab of your request and toggle off the Automatically follow redirects option.

After that, you'll get the same response as in Apex. It will, however, return Location header https://dashboard.nbshare.io/api/v1/apps/reddit, there is where public api is moved to.

So you'll need to add https://dashboard.nbshare.io to Remote Site Settings and change endpoint in code:

request.setEndpoint('https://dashboard.nbshare.io/api/v1/apps/reddit');
3
  • Thanks Mariia! I will check it out now. Commented Jun 2, 2022 at 7:17
  • It worked like a charm! Once again, thank you for your help! Commented Jun 2, 2022 at 7:18
  • You are welcome) Commented Jun 2, 2022 at 7:34
0

You can try to get the URL on which request is getting redirected for that use the below code

HttpResponse response = http.send(request);
     if(response.getStatusCode()==301){
         String newLocation=response.getHeader('Location');
         System.debug(newLocation);
}

once you get the URL it has redirected, you can store that in remote site settings and then perform callout by changing endpoint to the newLocation

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .