Exposing Apex Methods as SOAP Web Services

By exposing them as SOAP web services, apex methods are available to external applications.

To make Apex methods available as SOAP web services, we must declare them within a global Apex class and use the "webservice" keyword. Salesforce will then automatically create a WSDL document for that class, which can be utilized by external applications to access the exposed web services.

Example

global class MyWebService {

    webservice static Id makeContact(String contactLastName, Account a) {

        Contact c = new Contact(lastName = contactLastName, AccountId = a.Id);

        insert c;

        return c.id;

    }

}

To generate the WSDL file for a Salesforce instance, we can simply append "?wsdl" to the instance URL, followed by the path to the Apex class. 

For example, the URL should look like https://yourinstance.salesforce.com/services/wsdl/class/MyWebService. Once you have the WSDL file, you can generate client code in your external application and invoke the SOAP web service methods.

Here are some factors to remember when using the keyword "webservice".

  1. Use the webservice keyword to define top-level methods and outer-class methods. You can’t use it to define a class or an inner class method.
  2. You cannot use the webservice keyword to define an interface or its methods and variables.
  3. System-defined enums cannot be used in Web service methods.
  4. You cannot use the webservice keyword in a trigger.
  5. All classes containing methods defined with the webservice keyword must be declared global. If a method or inner class is declared global, the outer, top-level class must also be global.
  6. Methods defined with the webservice keyword are inherently global. Any Apex code that has access to the class can use these methods. You can consider the webservice keyword as an access modifier that enables more access than global.
  7. Define any method that uses the webservice keyword as static.
  8. You cannot deprecate webservice methods or variables in managed package code.
  9. Because there are no SOAP analogs for certain Apex elements, methods defined with the webservice keyword cannot take the following elements as parameters. While these elements can be used within the method, they cannot be marked as return values. Maps , Sets, Pattern objects , Matcher objects , Exception objects
  10. Use the webservice keyword with any member variables you want to expose as part of a Web service. Do not mark these member variables as static.

Comments

Popular posts from this blog

Introduction to Salesforce Agent Script: Build Predictable AI Agents

Anti-Patterns in Salesforce Agentforce: What to Avoid When Building AI Agents

MCP vs. Traditional APIs: Choosing the Right Integration Approach