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 -
Next if you are calling from Button Click then ensure that Button behaviour is as below-
Ensure that you include appropriate JS files in the Script-
Method can be called as below -
If method accepts a parameter, the same can be passed in the third argument comma seperated as below -
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:
If you are calling from Outside Salesforce then I would suggest -
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