Simple Outbound REST API with XML Response using Apex in Salesforce

Remote Site Settings:


Visualforce Page:

<apex:page controller="RESTAPIXMLResponseController">
    <apex:form>
        <apex:pageBlock>
            <apex:pageBlockSection>
                <apex:pageBlockSectionItem>Customer No: <apex:inputText value="{!strCustomerNo}"/></apex:pageBlockSectionItem>
            </apex:pageBlockSection>
            
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Fetch" action="{!fetchAPI}"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
        
        <apex:pageBlock>
            <apex:repeat value="{!mapCustomer}" var="c">
                {!c} - {!mapCustomer[c]}<br/>                 
            </apex:repeat>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Class:

public with sharing class RESTAPIXMLResponseController {

    public String strCustomerNo {get;set;}
    public Map < String, String > mapCustomer {get;set;}
    
    public RESTAPIXMLResponseController() {
    
    }
    
    public void fetchAPI() {
        mapCustomer = new Map < String, String >();
        String endpoint = 'http://www.thomas-bayer.com/sqlrest/CUSTOMER/' + strCustomerNo + '/';
        HTTP h = new HTTP();
        HTTPRequest req = new HTTPRequest();
        req.setEndPoint(endpoint);
        req.setMethod('GET');
        HTTPResponse res = h.send(req);
        Dom.Document doc = res.getBodyDocument();
        Dom.XMLNode customer = doc.getRootElement();
        for ( Dom.XMLNode child : customer.getChildElements() ) 
            mapCustomer.put(child.getName(), child.getText());
    }
    
}

Output:


Cheers!!!

No comments:

Post a Comment