Thursday, February 15, 2018

Apex Webservice (You Call me)

I already write about Apex Call Out when we want to connect with external services either in REST or SOAP here .

If Apex Call Out I use 'I call you' metaphor to represent Salesforce need to contact external service, therefore we need external service info such as - url and set end point url in Remote Site Setting.

While Apex Web Service I use 'You call me' which mean we need to expose our Apex class either as SOAP or REST for external service to connect.

You call me! In order for them to you,
you need to give your phone number

Expose a class as REST Service

  1. Define class with global access modifier .
  2. Use @RestResource annotation at class level to enable it serve as webservice
    • Example : @RestResource(urlMapping='/Case/*')
  3. Define method with global static .
  4. Add an annotation to associate with Http method. Bear in mind on one method is allowed per class. It means there should be only one GET method per class.
  5. Endpoint URL that we need to share to external service will look like this:*
@HttpGetReadReads or retrieves records.
@HttpPostCreateCreates records.
@HttpDeleteDeleteDeletes records.
@HttpPutUpsertTypically used to update existing records or create records.
@HttpPatchUpdateTypically used to update fields in existing records.
global with sharing class MyRestResource {
    global static Case getRecord() {
        // Add your code

Expose a class as SOAP Service

  1. Define class with global access modifier .
  2. Define your method with 'webservice static'
  3. You need to generate WSDL and send it to the external developer so they can write integration to connect wit us.
global class Project {
   webservice String area; 
   webservice String region; 
   //Define an object in apex that is exposed in apex web service
   global class Plan {
      webservice String name;
      webservice Integer planNumber;
      webservice Date planningPeriod;
      webservice Id planId;

   webservice static Plan createProjectPlan(Plan vPlan) {
       //A plan maps to the Project__c object in 
       //So need to map the Plan class object to Project__c standard object
       Project__c proj = new Project__c();
       proj.Name =;
       proj.AccountNumber = String.valueOf(vPlan.planNumber);
       insert proj;
       return vPlan;


This entry explains on custom Apex code for REST and SOAP API and it not the only way for external applications to connect with Salesforce. There a few ways to connect such as using Salesforce's REST and SOAP APIs. It has different strengths to fulfill  business requirement.

References :
Awesome Trailhead Apex Web Services
Still standing : Apex Web Services and Callouts

No comments:

Post a Comment