I am currently working on creating a REST API for an external service to call and create a new case object in my salesforce environment. This is the code I have created so far. However, due to my little REST knowledge, I am a bit stuck and not actually sure if the code is doing what I want it to do i.e. authenticate user's name, credentials, etc and then insert a new case object once authenticated.
@RestResource(urlMapping='/services/data/v29.0/sobjects/Case/')
global class publicStuffHttpRest {
String accessToken;// OAuth 2.0 access token
String sfdcInstanceUrl;// Endpoint URL for SFDC instance
private HttpResponse send(String uri, String httpMethod, String body) {
if (Limits.getCallouts() == Limits.getLimitCallouts())
throw new MyException('[HTTP-00] Callout limit: ' + Limits.getCallouts() + ' reached. No more callouts permitted.');
Http h = new Http();
HttpRequest hRqst = new HttpRequest();
hRqst.setEndpoint(uri);// caller provides, this will be a REST resource
hRqst.setMethod(httpMethod);// caller provides
hRqst.setTimeout(6000);
if (body != null)
hRqst.setBody(body);// caller provides
if (this.accessToken != null)// REST requires using the token, once obtained for each request
hRqst.setHeader('Authorization','Bearer ' + this.accessToken);
return h.send(hRqst);// make the callout
}
public class MyException extends Exception{}
@HttpPost
public void authenticateByUserNamePassword(String consumerKey, String consumerSecret, String uName, String uPassword) {
String uri = 'https://.salesforce.com/services/oauth2/token';
String clientId = EncodingUtil.urlEncode(consumerKey,'UTF-8');
String clientSecret = EncodingUtil.urlEncode(consumerSecret,'UTF-8');
String username = EncodingUtil.urlEncode(uName,'UTF-8');
String password = EncodingUtil.urlEncode(uPassword,'UTF-8');
String body = 'grant_type=password&client_id=' + clientId + '&client_secret=' + clientSecret +'&username=' + username + '&password=' + password;
HttpResponse hRes = this.send(uri,'POST',body);
if (hRes.getStatusCode() != 200)
throw new MyException('[HTTP-01] OAuth 2.0 access token request error. Verify username, password, consumer key, consumer secret, isSandbox? StatusCode=' + hRes.getStatusCode() + ' statusMsg=' + hRes.getStatus());
//System.debug(FlowControl.getLogLevel(),'response body =\n' + hRes.getBody());
Map<String,String> res = (Map<String,String>) JSON.deserialize(hRes.getBody(),Map<String,String>.class);
this.accessToken = res.get('access_token'); // remember these for subsequent calls
this.sfdcInstanceUrl = res.get('instance_url');
}
}
Any help on this