[SalesForce] how to call rest API from Html or javascript

i have one rest class for insert account , it's working with workbench.developerforce.com

but now i want to call same using HTML or JavaScript , how can i do ?

My Code :

@RestResource(urlMapping='/*')
global class InsertAccount{
@Httppost
global static String InsertAccount()
{  


    // Insert Account Using Post Method


    Account  acc = new Account();
    String jsonStr = null;

    if (null != RestContext.request.requestBody){

    jsonStr = RestContext.request.requestBody.toString();
    Map<String, object> m = (Map<String, object>)JSON.deserializeUntyped(jsonStr );
    system.debug('******'+m );
    acc.Name=(String)m.get('AccountName');
    insert acc;
   }
    return 'Account Inserted';
}


 @HttpGet
global static String InsertAccountRest()
{   

           // Insert Account Using Get Method

    Account  acc1 = new Account();
    acc1.Name=RestContext.request.params.get('AccountName');
    insert acc1;

    return 'Account Inserted';
}

}

Best Answer

First of all, ensure that your Class is global and method is webservice like below -

global class MyClass
{
    webservice static void myMethod() // you can pass parameters
    { 
         // Do something
    }
}

Next if you are calling from Button Click then ensure that Button behaviour is as below-

  • Behaviour : Execute Javascript
  • Content source : On-Click Javascript

Ensure that you include appropriate JS files in the Script-

{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")}

Method can be called as below -

sforce.apex.execute("MyClass","myMethod",{}"});

If method accepts a parameter, the same can be passed in the third argument comma seperated as below -

   sforce.apex.execute("MyClass","myMethod",{requestString:"Sample Request",endpoint:"www.a.com/b"}"});

Now if you are calling from a VF page then the code remains same but ensure that you have added scripts to the top as below:

<apex:includeScript value="/soap/ajax/30.0/connection.js"/>
<apex:includeScript value="/soap/ajax/30.0/apex.js"/>

If you are calling from Outside Salesforce then I would suggest -

  1. Setting OAUTH in salesforce by creating a connected App. (App Setup>Create>Apps)
  2. Change the URL mapping to the top to display appropriate URL. ( This will be endpoint)
  3. then you can use either Curl or SOAP UI tool or hurl.it to check if your class gives proper response.

The process is bit lengthy to explain, and I found a good link that sums it all - http://www.oyecode.com/2014/08/start-building-your-own-rest-api-in.html

Related Topic