Creating Custom Apex REST APIs with Force.com

C

Suppose we want to expose Opportunity object through Rest Web Service.

Step 1 : Create a class like below

@RestResource(urlMapping=’/FieldOpportunity/*’)
global with sharing class RESTOppController
{
@HttpGet
global static List<Opportunity> getOpenOpportunities()
{
String OpportunityName = RestContext.request.params.get(‘OpportunityName’);
Opportunity opp = [ Select ID, Name, Amount from Opportunity where Name = :OpportunityName];
List<Opportunity> OppList = [SELECT Id, CloseDate,StageName, Type,  LeadSource from Opportunity WHERE Name =: Opp.Name];
return OppList;
}
}

Step 2: Create Force.com sites. It  enable you to create public websites and applications. Under App Setup expand Develop and click Sites.

Step 3: Choose a Force.com domain name. Ensure it is available, click the checkbox, then click Register My Force.com Domain.

Step 4: Once your site is registered click the New button.

Step 5:    Give yourself a Site LabelSite Name, and choose an Active Site Home Page. Since no one will use this site as a website I’ve chosen FileNotFound. Click the Save button.

Step 6: By default the site is not active. Click the Activate button or else you will not be able to access your APIs.

Step 7: Next we have to grant anonymous access to our Apex REST API. Click thePublic Access Settings button.

Step 8: Scroll down the Standard Object Permissions and check all checkbox of Opportunity and click on Save button.

Step 9: Scroll down to Enabled Apex Class Access and click the Edit button. Select the RESTOppController and click the Add button. Click Save.

Step 10: Get the url from your site that you have created and put that url to the url bar of your brouser. The url looks like https://yoursitename-developer-edition.ap2.force.com/services/apexrest/FieldOpportunity?OpportunityName=opp_name_that_available_inYour_Org

About the author

rajesh.chatterjee
By rajesh.chatterjee

Category