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.

    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
        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{}

    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


The part that you need to write in Apex is this:

// You can choose the mapping path (better to not confuse by copying other Salesforce paths)
global class publicStuffHttpRest {
    global static Case createCase(String origin, String SuppliedEmail, String SuppliedName,
            String SuppliedPhone, String Description, Integer publicStuff_reqId,
            Boolean hasExternalAttachments, String Status
             ) {
        Case newCase = new Case();
        newCase.origin = 'Web'; 
        newCase.SuppliedEmail = SuppliedEmail; 
        newCase.SuppliedName = SuppliedName; 
        newCase.SuppliedPhone = SuppliedPhone;
        newCase.Description = Description; 
        newCase.publicStuff_reqId__c = publicStuff_reqId;
        newCase.hasExternalAttachments__c = hasExternalAttachments; 
        newCase.Status = Status;
        insert newCase;
        return newCase;

Take care with the method parameter names you use though as they become part of the API. Some more consistent casing would be better.

Given the above code, other code can just POSTa JSON String of this form to your API (no fancy tooling or libraries required):

{"origin": "xxx", "SuppliedEmail": "yyy", :SuppliedName": "zzz", ...}

The authentication is not something you have to write Apex code for. A client's request won't get routed to your Apex class unless the request is authenticated. (Authentication is usually handled via values in the HTTP headers not values in the HTTP body.)

Ditto on Roark's suggestion - chapters such as "Step Two: Set Up Authorization" in the Force.com REST API Developer's Guide.


Have you read through the first two chapters of the REST API documentation? There is very good explanation of how authentication works. https://www.salesforce.com/us/developer/docs/api_rest/.

  • this is not really an answer and, per the style of this SFSE site, more appropriately belongs as a comment to the OP – cropredy Nov 25 '14 at 20:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.