Saturday, July 28, 2012

REST API:

REST API:
This article shows how to use webservice callout by REST API.The first thing you need to make your destination url in remote site settings.In this example i call my own domain destination so you can try same with your domain since it will ask permission before you call your destination and you need to allow the source first time call.So the destination gave response by creating some target class like this

@RestResource(urlMapping='/GetService/*')   global with sharing class getservice1 {       @HttpGet      global static String getRestMethod()      {           RestRequest req = RestContext.request;         RestResponse res = RestContext.response;         String name = req.params.get('name');         return 'Hello '+name+', you have just invoked a custom Apex REST web service exposed
 using REST API' ;     } }

Once you finish your destination response now come back to your source and try establish call out from source like this

public abstract class OAuthRestController {
    static String clientId = '3MVG9zeKbAVObYjM0ERpVyn5vpvdS7P0qclqomMNsU03lguvoqJl5TRRSiee5lFk__5w2.4jvZzvGxJs2biQ3'; // Set this in step 3
    static String clientSecret = '7933821080022371323'; // Set this in step 3
    static String redirectUri = 'https://rajkumar-dev-ed.my.salesforce.com/apex/RestCall'; // YOUR PAGE URL IN THE SOURCE ORG
    static String loginUrl = 'https://kakumanu-dev-ed.my.salesforce.com/'; // YOUR MY DOMAIN URL IN THE TARGET ORG
    static String cookieName = 'oauth';

    public PageReference login() {
        // Get a URL for the page without any query params
        String url = ApexPages.currentPage().getUrl().split('\\?')[0];
     
        System.debug('url is '+url);

        String oauth = (ApexPages.currentPage().getCookies().get(cookieName) != null ) ?
            ApexPages.currentPage().getCookies().get(cookieName).getValue() : null;
        if (oauth != null) {
            // TODO - Check for expired token
        }
     
        System.debug('oauth='+oauth);
        if (oauth != null) {
            // All done
            return null;
        }
     
        // If we get here we have no token
        PageReference pageRef;
     
        if (! ApexPages.currentPage().getParameters().containsKey('code')) {
            // Initial step of OAuth - redirect to OAuth service
            System.debug('OAuth Step 1');
     
            String authuri = loginUrl+'/services/oauth2/authorize?'+
                'response_type=code&client_id='+clientId+'&redirect_uri='+redirectUri;
                         
            pageRef = new PageReference(authuri);
        } else {
            // Second step of OAuth - get token from OAuth service
            String code = ApexPages.currentPage().getParameters().get('code');

            System.debug('OAuth Step 2 - code:'+code);
             
            String body = 'grant_type=authorization_code&client_id='+clientId+
                '&redirect_uri='+redirectUri+'&client_secret='+clientSecret+
                '&code='+code;
            System.debug('body is:'+body);
             
            HttpRequest req = new HttpRequest();
            req.setEndpoint(loginUrl+'/services/oauth2/token');
            req.setMethod('POST');
            req.setBody(body);
     
            Http h = new Http();
            HttpResponse res = h.send(req);
 
            String resp = res.getBody();
            System.debug('FINAL RESP IS:'+EncodingUtil.urlDecode(resp, 'UTF-8'));
         
            ApexPages.currentPage().setCookies(new Cookie[]{new Cookie(cookieName,
                res.getBody(), null,-1,false)});
             
            // Come back to this page without the code param
            // This makes things simpler later if you end up doing DML here to
            // save the token somewhere
            pageRef = new PageReference(url);
            pageRef.setRedirect(true);
        }
     
        return pageRef;
    }
 
    public static String getRestTest() {
        String oauth = (ApexPages.currentPage().getCookies().get(cookieName) != null ) ?
            ApexPages.currentPage().getCookies().get(cookieName).getValue() : null;
        JSONObject oauthObj = new JSONObject( new JSONObject.JSONTokener(oauth));
         
        String accessToken = oauthObj.getValue('access_token').str,
               instanceUrl = oauthObj.getValue('instance_url').str;

        HttpRequest req = new HttpRequest();

        req.setMethod('GET');
        req.setEndpoint(instanceUrl+'/services/apexrest/GetService/getservice1?name=Kumar');
        req.setHeader('Authorization', 'OAuth '+accessToken);

        Http http = new Http();

        HTTPResponse res = http.send(req);

        System.debug('BODY: '+res.getBody());
        System.debug('STATUS:'+res.getStatus());
        System.debug('STATUS_CODE:'+res.getStatusCode());
     
        return res.getBody();
    }
}


for the above example you need your source org client id and client that you can get by creating a simple remote access from your app setup.This example is sending a name (kumar) to the destination org and getting some message as a response from target.So time for displaying response on visualforce like this

<apex:page controller="OAuthRestController" action="{!login}" showHeader="true">
  <h1>Rest Test</h1>
  getRestTest says "{!restTest}"
</apex:page>

No comments:

Post a Comment