Did you know you can expose your APEX classes to the outside world? This is great for all kinds of things, for example if you want to integrate to your Salesforce system and have logic applied to it before inserting it to your database.
Say you have an external project management tool, and you want Opportunities in Salesforce to be updated once a project reaches a certain stage. The external tool creates a JSON payload, which is then send to a custom Salesforce endpoint which you created!
Here’s an example of a very simple web service which creates a Lead :
@RestResource(urlMapping='/leads/*')
global with sharing class LeadRESTService {
@HttpPost
global static String createLead(
String lastname,
String firstname,
String email) {
try {
Lead lead = new Lead(
LastName = lastname,
FirstName = firstname,
Email = email);
upsert lead Email;
return 'OK';
} catch(Exception e) {
Database.rollback(savepoint);
return e.getMessage()
}
Let’s walk through this code. First, every web service always starts with defining that it’s a web service with @RestResource. It’s followed by the urlMapping, which will be used for the external tool to send it’s payload to. In this case it would be “yourDomain.my.salesforce.com/services/apexrest/leads”.
We then have to provide which method we are using, which is HttpPost. You can find all other options here.
Next comes the method, which in this case returns a String. It accepts a JSON payload as it’s parameter, defined by:
String lastname,
String firstname,
String email
We then try creating a new Lead by using this input. It’s as simple as setting the fields of the Lead to the Strings you determined earlier! Instead of inserting the Lead, we do an upsert on Email, in case there is already a Lead present with that email address. This keeps our data nice and clean! If everything goes well, the method returns a simple ‘OK’ string. This can obviously be expanded but for now this works!
But what if it doesn’t work as expected? We are implementing a Try/Catch principle in which we catch generic Exceptions. This would normally be a bit too broad, and a better approach would be to plan for specific Exceptions which occur. In this catch block, the exception gets caught, and the error message is returned. That way the external system will know it failed, and why exactly!
And that’s all there is to it. Bear in mind that this is a very simple example, and can be extended to do a lot more than just creating a new Lead. But this should get you started on your way to developing a bunch of cool web services!