Method: POST
Header: Content-Type =
application/x-www-form-urlencoded
In Body:
grant_type=password&client_id=<Consumer_key_from_ConnectedApp>&client_secret=<Consumer_Secret_from_ConnectedApp>&username=<username of sf org>&password=<password of sf org+security token>
Following is the response:
@RestResource(urlMapping='/Account/*') global with sharing class MyRestResource { @HttpDelete global static void doDelete() { RestRequest req = RestContext.request; RestResponse res = RestContext.response; String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1); Account account = [SELECT Id FROM Account WHERE Id = :accountId]; delete account; } @HttpGet global static Account doGet() { RestRequest req = RestContext.request; RestResponse res = RestContext.response; String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1); Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE Id = :accountId]; return result; } @HttpPost global static String doPost(String name, String phone, String website) { Account account = new Account(); account.Name = name; account.phone = phone; account.website = website; insert account; return account.Id; } }
This is how to consume these API's
Test GET Method
The Header of the actual callout will be: -
Authorization: Bearer <access_token>
URL
https://virajlearningsf1-dev-ed.my.salesforce.com/services/apexrest/Account/<account id>
Following would be the response:
{ "attributes": { "type": "Account", "url": "/services/data/v47.0/sobjects/Account/0017F00000I8KqPQAV" }, "Id": "0017F00000I8KqPQAV", "Name": "Grand Hotels & Resorts Ltd", "Phone": "(312) 596-1000", "Website": "www.grandhotels.com" }
Test POST Method
Headers:
The Header of the actual callout will be: -
Authorization: Bearer <access_token>
URL
https://virajlearningsf1-dev-ed.my.salesforce.com/services/apexrest/Account/<account id>
Select Method as DELETE.
This would delete the account who's id is passed in URL
To make this integration Wrapper based, which is recommended to make it generic,
following changes need to be made.
1] Create a utility class
Global class APIUtility { public APIUtility() { } Global class Wrapper { public String name; public String phone; public String website; } }
2] Update post method to use wrapper instead of separate parameters
@HttpPost global static String doPost(APIUtility.Wrapper Data) { if(Data != null) { Account account = new Account(); account.Name = Data.name; account.phone = Data.phone; account.website = Data.website; insert account; return account.Id; } return ''; }
3] Pass following in body while consuming API
{ "Data" :{ "name" : "Wingo Ducks", "phone" : "707-555-1234", "website" : "www.wingo.ca.us" } }