Exposing Apex Classes as REST Web Services
- johnsontitus
- Jun 15, 2020
- 2 min read
Steps to expose your Apex class and methods to external applications:
#
Define the Apex class with the @RestResource(urlMapping='/yourUrl') annotation
#
Define Apex methods with the following annotation depending on the operation you want to provide:
@HttpDelete eg,@HttpDelete global static Account doDelete(){}
@HttpGet - should have no parameters. eg,@HttpGet global static Account doGet(){} Note: should have no parameters. This is because GET and DELETE requests have no request body, so there's nothing to deserialize.
Apex REST Methods:
Apex REST supports two formats for representations of resources:
JSON and XML.
JSON representations are passed by default in the body of a request or response, and the format is indicated by the Content-Type property in the HTTP header.
You can retrieve the body as a Blob from the HttpRequest object if there are no parameters to the Apex method.
Eg:
@HttpPost
global static String createCase() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
try{
Blob reqBody = req.requestBody;
System.debug('request body ' + reqBody.toString());
}
catch(Exception e){
return e.getStackTraceString();
}
return 'success';
}
If the Apex method has a non-void return type, the resource representation is serialized into the response body.
These return and parameter types are allowed:
Apex primitives (excluding sObject and Blob).
sObjects
Lists or maps of Apex primitives or sObjects (only maps with String keys are supported).
User-defined types that contain member variables of the types listed above.
Note: Single Apex class annotated with @RestResource can't have multiple methods annotated with the same HTTP request method. For example, the same class can't have two methods annotated with @HttpGet.
RestRequest and RestResponse objects are available by default in your Apex methods through the static RestContext object. This example shows how to access these objects through RestContext:
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
method with parameters - POST or PUT, Apex REST attempts to deserialize the data into those parameters and the data won't be deserialized into the RestRequest.requestBody property.
An Apex method with a non-void return type will have the return value serialized into RestResponse.responseBody.
Governor Limits:
Description Synchronous Limit Asynchronous Limit
Total number of callouts
(HTTP requests or web
services calls) in a tnx 100
Maximum cumulative
timeout for all callouts
(HTTP requests or
Web services calls) in
a transaction 120 seconds
Maximum size of callout
request or response (HTTP
request or Web services
call) 16 MB 12 MB
To invoke Apex REST in Mule:
https://help.mulesoft.com/s/article/How-to-invoke-APEX-REST-and-SOAP-method-using-Salesforce-Connector


Comments