I am new to salesforce. I created an apex class and exposed it as a Rest service. I want to post some parameters to that service from an external client(not vf page). One way is I append it to the url something like myservice/functionName/parameter1/parameter2. But I want to send them as GET/POST parameters. Does anyone know how to read those parameters in the apex class?
4 Answers
Rather than accept say form encoded parameters it is usually more convenient (for the client and in the Apex code) to accept a JSON string that holds the parameters. For the POST case:
@HttpPost
global static Result post() {
String jsonString = RestContext.request.requestBody.toString();
// Use Apex JSON class to parse
...
}
For GET parameters you have to do your own string manipulation of the URL that you can obtain from the static field RestContext.request.requestURI
. (Or better use params
as Jitendra illustrates.)
If you want to test the REST API below:
@RestResource (urlMapping='/wte/test/*')
global class WTE_SampleRESTService {
@HttpGet
global static void doGet() {
String id = RestContext.request.params.get('id');
System.debug('ID: '+ id);
}
@HttpPost
global static void doPost(String id, String name) {
System.debug('ID: '+id+', Name: '+name);
}
}
You can use Workbench or curl.
above image shows Testing using Workbench
This post might be very helpful for you.
The following apex class example will allow you to set parameters in the query string for a post request -
@RestResource(urlmapping = '/sendComment/*')
global without sharing class postComment {
@HttpPost
global static void postComment(){
//create parameters
string commentTitle = RestContext.request.params.get('commentTitle');
string textBody = RestContext.request.params.get('textBody');
//equate the parameters with the respective fields of the new record
Comment__c thisComment = new Comment__c(
Title__c = commentTitle,
TextBody__c = textBody,
);
insert thisComment;
RestContext.response.responseBody = blob.valueOf('[{"Comment Id":
'+JSON.serialize(thisComment.Id)+', "Message" : "Comment submitted
successfully"}]');
}
}
The URL for the above API class will look like -
/services/apexrest/sendComment?commentTitle=Sample title&textBody=This is a comment
You would be better off by using the Composite API to achieve this.