I wish to create an apex code in Salesforce that take input from users and then these inputs will be sent to an external API (this API will convert the input to JSON format).
1) User will input a sentence 2) Send it to external API and it will process the input to JSON file 3) retrieve JSON file 4) deserialize the JSON file - COMPLETED
Is there anyone who has exprience in using Salesforce apex coding?
My page is as below:
<apex:page id="page" controller="calloutViewer_Controller" >
<apex:form id="form" >
<apex:sectionHeader title="Testing" />
<apex:pageMessages id="pageMessages" />
<apex:pageBlock >
<apex:pageBlockButtons >
<apex:commandButton value="Callout" action="{!callout}" rendered="{!$CurrentPage.parameters.offline!='1'}"/>
<apex:commandButton value="Deserialize" action="{!deserializeQuestions}" rendered="{!$CurrentPage.parameters.offline!='1'}"/>
<apex:commandButton value="Callout (offline)" action="{!callout}" rendered="{!$CurrentPage.parameters.offline=='1'}" />
<apex:commandButton value="Deserialize (offline)" action="{!deserializeQuestions}" rendered="{!$CurrentPage.parameters.offline=='1'}" />
</apex:pageBlockButtons>
<apex:pageBlockSection columns="1" title="HttpRequest" collapsible="false" >
<apex:pageBlockSectionItem >
<apex:outputLabel value="setMethod()" />
<apex:selectList size="1" value="{!requestMethod}" >
<apex:selectOptions value="{!MethodOptions}" />
</apex:selectList>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="setEndpoint()" />
<apex:inputText value="{!requestEndpoint}" style="width:90%" />
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputText>{!getBody}</apex:outputText>>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:pageBlockSection columns="1" title="HttpResponse" collapsible="false" >
<apex:pageBlockSectionItem >
<apex:outputLabel value="getStatusCode()" />
<apex:outputText value="{!responseStatusCode}" />
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="getStatus()" />
<apex:outputText value="{!responseStatus}" />
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="getBody()" />
{!responseBody}
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:pageBlockSection columns="1" title="JSON Deserializer" rendered="{!deserializedQuestions != null}" collapsible="false" >
<apex:pageBlockTable value="{!deserializedQuestions}" var="i" >
<apex:column headerValue="Owner" style="width:100px;" >
<apex:outputLink value="{!i.owner.link}" target="_blank" style="width:100px;" >
<apex:image value="{!i.owner.profile_image}" alt="{!i.owner.display_name}" style="height:30%; width:30%;" /><br/>{!i.owner.display_name}
</apex:outputLink>
</apex:column>
<apex:column headerValue="Question Id" style="width:75px;" >
<apex:outputText value="{!i.question_id}" />
</apex:column>
<apex:column headerValue="Creation Date" style="width:75px;" >
<apex:outputText value="{!i.creation_date}" />
</apex:column>
<apex:column headerValue="View Count" style="width:75px;" >
<apex:outputText value="{!i.view_count}" />
</apex:column>
<apex:column headerValue="Answer Count" style="width:75px;" >
<apex:outputText value="{!i.answer_count}" />
</apex:column>
<apex:column headerValue="Score" style="width:50px;" >
<apex:outputText value="{!i.score}" />
</apex:column>
<apex:column headerValue="Title" >
<apex:outputLink value="{!i.link}" target="_blank" ><apex:outputText value="{!i.title}" /></apex:outputLink>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
My apex controller:
public with sharing class calloutViewer_Controller {
public String requestEndpoint {get;set;}
public String requestMethod {get;set;}
public String requestBody {get;set;}
public String responseStatus {get;set;}
public Integer responseStatusCode {get;set;}
public String responseBody {get;set;}
public stackExchangeAPI.responseResource response {get;set;}
public List<stackExchangeAPI.questionResource> deserializedQuestions {get;set;}
public calloutViewer_Controller(){
requestEndpoint = stackExchangeAPI.compileEndpoint(
'questions/unanswered',
'salesforce',
1,
50,
system.today().addDays(-1),
system.today(),
'desc',
system.today().addDays(-1),
system.today(),
'activity',
''
);
}
public void callout(){
httpResponse res = stackExchangeAPI.callout(requestMethod, requestEndpoint, requestBody);
responseStatus = res.getStatus();
responseStatusCode = res.getStatusCode();
responseBody = res.getBody();
}
public void deserializeQuestions(){
if ( string.isNotBlank(responseBody) ){
response = (stackExchangeAPI.responseResource)JSON.deserialize(responseBody,stackExchangeAPI.responseResource.class);
deserializedQuestions = response.items;
}
}
public List<SelectOption> getMethodOptions(){
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('GET','GET'));
options.add(new SelectOption('POST','POST'));
options.add(new SelectOption('PUT','PUT'));
options.add(new SelectOption('DELETE','DELETE'));
options.add(new SelectOption('HEAD','HEAD'));
return options;
}
}
My apex class:
public with sharing class stackExchangeAPI {
public static String BASE_URL = 'https://api.stackexchange.com/2.2/';
//Method to perform a callout and return an httpResponse
public static httpResponse callout(String httpMethod, String endpoint, String body){
//Instantiate an httpRequest and set the required attributes
httpRequest req = new httpRequest();
req.setMethod(httpMethod);
req.setEndpoint(endpoint);
//Optional attributes are often required to conform to the 3rd Party Web Service Requirements
req.setHeader('Accept-Encoding','gzip, deflate');
//You can adjust the timeout duration (in milliseconds) to deal with slow servers or large payloads
req.setTimeout(120000);
//Use the HTTP Class to send the httpRequest and receive an httpResposne
/*If you are not using an HttpCalloutMock:
if (!test.isRunningTest){
*/
httpResponse res = new http().send(req);
/*If you are not using an HttpCalloutMock:
}
*/
system.debug(res.toString());
system.debug(res.getBody());
return res;
}
//Method to deserialize the response body
public static responseResource deserialize(httpResponse res){
return (responseResource)JSON.deserialize(res.getBody(),responseResource.class);
}
/********************* Apex Inner Classes to represent StackExchange objects ***********************/
//Outermost class included in the response from StackExchange
public class responseResource {
public Integer error_id {get;set;}
public String error_message {get;set;}
public String error_name {get;set;}
public Boolean hasMore {get;set;}
public List<questionResource> items {get;set;}
public Integer quote_max {get;set;}
public Integer quote_remaining {get;set;}
}
//Class to represent a question posted on StackExchange
public class questionResource {
public List<String> tags {get;set;}
public userResource owner {get;set;}
public Boolean is_answered {get;set;}
public Integer view_count {get;set;}
public Integer answer_count {get;set;}
public Integer score {get;set;}
public long last_activity_date {get;set;}
public long creation_date {get;set;}
public long last_edit_date {get;set;}
public integer question_id {get;set;}
public String link {get;set;}
public String title {get;set;}
}
//Class to represent a registered User of StackExchange
public class userResource {
public String reputation {get;set;}
public String user_id {get;set;}
public String user_type {get;set;}
public String profile_image {get;set;}
public String display_name {get;set;}
public String link {get;set;}
}
/********************* Other Useful Methods ***********************/
// http://api.stackexchange.com/2.2/questions/unanswered?page=1&pagesize=50&fromdate=1396310400&todate=1398816000&order=desc&min=1396310400&max=1397606400&sort=activity&tagged=google-compute-engine&site=stackoverflow
public static responseResource questions_Unanswered(String site, Integer page, Integer pagesize, Date fromdate, Date todate, String order, Date min, Date max, String sortParam, String tagged){
httpResponse res = callout('GET', compileEndpoint('questions/unanswered',site,page,pagesize,fromdate,todate,order,min,max,sortParam,tagged) , null);
if ( res.getStatusCode() == 200 && string.isNotBlank(res.getBody()) ){
return deserialize(res);
}
return null;
}
public static String compileEndpoint(String call, String site, Integer page, Integer pagesize, Date fromdate, Date todate, String order, Date min, Date max, String sortParam, String tagged){
PageReference endpoint = new PageReference(BASE_URL+call);
if ( string.isNotBlank(site) ){
endpoint.getParameters().put('site',site);
}
if ( page != null && page > 0 ){
endpoint.getParameters().put('page',string.valueOf(page));
}
if ( pagesize != null ){
endpoint.getParameters().put('pagesize',string.valueOf(pagesize));
}
if ( fromdate != null ){
endpoint.getParameters().put('fromdate',string.valueOf(dateTime.newInstance(fromdate,time.newInstance(0,0,0,0)).getTime()/1000));
}
if ( todate != null ){
endpoint.getParameters().put('todate',string.valueOf(dateTime.newInstance(todate,time.newInstance(0,0,0,0)).getTime()/1000));
}
endpoint.getParameters().put('order','desc');
if ( string.isNotBlank(order) ){
endpoint.getParameters().put('order',order);
}
if ( min != null ){
endpoint.getParameters().put('min',string.valueOf(dateTime.newInstance(min,time.newInstance(0,0,0,0)).getTime()/1000));
}
if ( max != null ){
endpoint.getParameters().put('max',string.valueOf(dateTime.newInstance(max,time.newInstance(0,0,0,0)).getTime()/1000));
}
endpoint.getParameters().put('sort','activity');
if ( string.isNotBlank(sortParam) ){
endpoint.getParameters().put('sort',sortParam);
}
if ( string.isNotBlank(tagged) ){
endpoint.getParameters().put('tagged',tagged);
}
return endpoint.getURL();
}
}
How can I alter my code so that there is another pageblockitem such as "Input" and then the controller will take this input and send it to the server. Lastly, use setMethod("GET") to return the JSON file before deserialized it?