We created a REST Service in Salesforce in our previous blog, and now we want to call the REST service from another application. Salesforce DO NOT allow using Basic Authentication (Username & Password) for incoming REST calls. This is still true even if you are calling from another Salesforce instance. We have to use OAuth to authenticate to Salesforce.
OAuth (Open Authorization) is an open protocol to provide secured authorization. Here are the list of OAuth flows used while making REST API calls:
- Web server flow, where the server can securely protect the consumer secret. more…
- Username-password flow, where the application has direct access to user credentials. more…
- User-agent flow, used by applications that cannot securely store the consumer secret. more…
In this blog, we are using Username-password flow to make a call to a REST Service in Salesforce using OAuth. Please follow the steps below to set up the REST call:
1) Remote Site Settings
First you need to create two entries in remote site settings:
- Enter the remote site Name, URL for Salesforce login https://login.salesforce.com
- Create another remote site Name, URL for accessing Salesforce data https://instance.salesforce.com.
2) Create Connected App
Now we create a Connected App:
- Go to Setup | Create | Apps.
- Under Connected App, Click “New”.
- Enter the name of Connected App and specify details as mentioned (in Screenshot) below.
- Click Save.
Once you have created the Connected App, you will see the following screen with “Consumer Key” and “Consumer Secret”:
We can use the “Consumer Key” which will be a client_id and “Consumer Secret” as client_secret inside the body of the call to make the callout.
grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password
Apex Code:-
/* Class for getting account record from other salesforce org through rest api integration by calling class and its method from other org*/ public class MyCalloutService{ public MyCalloutService(){ //You will get "clientId","clientSecret" when creating connected app in salesforce String clientId = '3MVG9szVa2RxsqBYoWov5yC4I5MxFgDDe3.6Z1g__FlEYNOPY45vALm1kA5oCZuFkHYxCzm2A3SdSoxFpUNU3'; String clientSecret = '7917982719268332943'; //We can also store our username password in custom setting. String username='ajomon@apexcoder.com';//salesforce username String password='*l2YzP2TxlvI';//EUe4eHjMxXb8UFco1SPcpsZL9';//salesforce password // Generating the Access Token HttpRequest req = new HttpRequest(); req.setMethod('POST'); req.setEndpoint('https://login.salesforce.com/services/oauth2/token');// this is the OAuth endpoint where this request will be hit req.setBody('grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password); Http http = new Http(); HTTPResponse res = http.send(req); String str = res.getBody(); wrapObj = (Wrapper)Json.deserialize(str,Wrapper.class); accessToken = wrapObj.access_token; instanceUrl = wrapObj.instance_url; methodGet(); } // Retrieve the Contacts from the otehr org. public void methodGet(){ HttpRequest req = new HttpRequest(); req.setMethod('GET'); //req.setEndpoint(wrapObj.instance_url+'/services/apexrest/Account/getAccountById?name=champaKAli'); req.setEndpoint(wrapObj.instance_url+'/services/apexrest/AccountService'); req.setHeader('Authorization', 'OAuth '+wrapObj.access_token); Http http = new Http(); HTTPResponse res = http.send(req); System.debug('***Response***** ' + res.getBody()); //---------------------Here ------------------ /*JSONParser parser = JSON.createParser(res.getBody()); do{ parser.nextToken(); }while(parser.hasCurrentToken() && !'records'.equals(parser.getCurrentName())); parser.nextToken(); List acc = (List) parser.readValueAs(List.class);*/ } public Contact con {get;set;} public String s1 {get;set;} public String accessToken; public String instanceUrl; public Wrapper wrapObj{get;set;} // Wrapper Class to Store the value from the Jason. public class Wrapper{ String id; String instance_url; String access_token; String issued_at; String signature; } }
In the above code, we are using client_id and client_secret to authorize the external app.
We can also parse the response using parser classes.
We can execute the above code using developer console and print all the accounts in system.debug() :
MyCalloutService tw = new MyCalloutService(); tw.methodGet();