Skip to main content
Hello, so i want to connect my visualforce page to a class that get something from an api. And that to be shown on the home page.

here my class code

 

public class CatFactsDaily {

public String catFact3{get;set;}

public void toGetFacts() {

String requestEndPoint = 'https://catfact.ninja/fact';

Http http=new Http();

HttpRequest request = new HttpRequest();

request.setEndpoint(requestEndPoint);

request.setMethod('GET');

HttpResponse response=http.send(request);

if(response.getStatusCode()==200){

Map<String, Object> results=(Map<String, Object>) JSON.deserializeUntyped(response.getBody());

catFact3=String.valueOf(results.get('fact'));

}

else {

ApexPages.Message myMsg=new ApexPages.Message(ApexPages.Severity.ERROR, 'There was an error in reading Data');

ApexPages.addMessage(myMsg);

}

}

}

here is my visualforce code

 

<apex:page controller="CatFactsDaily" >

<apex:pageBlock title="Cat Fact of the day!!">

<apex:pageBlockSection >

<apex:pageMessages ></apex:pageMessages>

<apex:outputText label="CatFact" value="{!catFact3}"></apex:outputText>

</apex:pageBlockSection>

</apex:pageBlock>

</apex:page>

and this is what i get

how to connect my visualforce page with a classI ve tried this same api with for and account, and it works, but i cannot make it work for the home page​​​​​​​
2 answers
  1. Dec 8, 2022, 6:22 AM
    Hi Marjan,

    The issue is that your toGetFacts method is never called. In order to do that you can add a constructor and call that method. Here is the entire class code. You also may need to define the RemoteSiteSettings for the EndPoint URL

     

    public class CatFactsDaily {

    public String catFact3{ get; set; }

    public CatFactsDaily(){

    toGetFacts();

    }

    public void toGetFacts() {

    String requestEndPoint = 'https://catfact.ninja/fact';

    Http http=new Http();

    HttpRequest request = new HttpRequest();

    request.setEndpoint(requestEndPoint);

    request.setMethod('GET');

    HttpResponse response=http.send(request);

    if(response.getStatusCode()==200){

    Map<String, Object> results=(Map<String, Object>) JSON.deserializeUntyped(response.getBody());

    catFact3=String.valueOf(results.get('fact'));

    }else {

    ApexPages.Message myMsg=new ApexPages.Message(ApexPages.Severity.ERROR, 'There was an error in reading Data');

    ApexPages.addMessage(myMsg);

    }

    }

    }

    Please don't hesitate to mark this best answer. 
0/9000