Setting up a REST API – Part 1

Setting up a REST API is actually a fairly easy thing to do and Salesforce have made it remarkably easy.

Let’s create a REST API to return all the records from a custom object Travel__c that has been developed in a few posts to date.

Fire up the Developer Console and we need a new APEX class – lets call it TravelResults.  We get a fairly basic stub of code:

This needs a few adjustments to get it into REST API mood:


@RestResource(urlMapping='/TravelResults/*')
global with sharing class TravelResults {

}

The first line gets the endpoint for our API call that we will make – by convention this is useful to have as the same urlMapping as the name of the class but there is no need for this.

The class can accept a POST or GET method and only one of each per class (we will see how to extend this soon).  Adding a @HttpGet or @HttpPost to a global static function in the class will then route any GET or POST calls to that function.

So


@RestResource(urlMapping='/TravelResults/*')
global with sharing class TravelResults {

@HttpGet
global static List<Travel__c> getTravel() {

}

@HttpPost
global static void createTravel(){

}
}

will be all the code we need t develop a REST API with POST and GET endpoints.

We want an extendable REST API such that if new fields get added to the object we need not get too directly and have to update the REST API each time.

The following code is a bit of a lifesaver and will get a list of the fields in an object:


//get object fields
List<String> fieldList = new List<String>(Schema.getGlobalDescribe().get('Travel__c').getDescribe().fields.getMap().keySet());
String fields = String.join(fieldList,',');

Travel__c being the object we want.

All this is needed as there is no concept of SELECT * FROM Table in Salesforce.

We can then do a database call


List<Travel__c> result = null;
result = database.query('SELECT '+fields+' FROM Travel__c');
return result;

The next post will show how to enable this via a connected app using OAuth 2.0 and then use a program called PostMan to make some test calls.

Leave a Reply

Your email address will not be published.