Saturday 23 January 2016

APEX REST Services !

What is REST?

  • It is Representation State Transfer
  • REST is a Architectural Style and NOT a protocol
  • REST is a Framework
  • It is HTTP Based (It is based on URLs, POST, GET )
  • It is Client-Server (Lost of Use-cases revolve around Mobile)
  • It is Stateless (Everycall does not have knowledge about previous calls. Each call lives as its own entity.)
It uses Standard HTTP Methods, sent to endpoint
Receive a response payload and Status in return
  • JSON or XML –> The response is already handled by Salesforce for use. So we don’t need to Serialize and De-Serialize it.
  • When we get that response back, we get the following response.
  • 200 (Ok) , 404 (Not Found) –> bit.ly/responsecodes
Commonly HTTP Verbs are mapped to CRUD Operations
  • POST –> Create
  • GET –> Read
  • DELETE –> Delete
  • PUT/ PATCH –> Update
  • For Example:
    • If I do a GET against “myAccountService” , its understood that someone is performing a search in Account .
    • That, I need to retrieve some information from the Database.
    • If I do POST, then I would be sending body of Information to create an Account.
Why use APEX REST?
  • All sObject, standard or Custom, comes with REST API.
  • Salesforce provides native API, that we can connect to and operate with that object from REST.
  • APEX REST used for defining Custom Interactions.
  • APEX REST is good for abstracting complex interactions to a single Call
    • Example: Inserting/ Updating multiple Objects
    • Callouts to External Systems
    • Custom Search Interfaces.
    • If we uses a Standard REST API, we would be using 2 Services.
      • Account Service to create an account and we would get the response from that
      • Then we would call the contact service and get the response from that.
    • With APEX REST, we can build all these in 1 call and create your Account and the Contact –> All at the Same time.
APEX Rest Basics:
There are custom Annotations which makes the APEX services work.
@RestResource(urlMapping=’/<Custom_Path>/*’)
  • Class Level Annotation
  • Class level annotation to define a Global Class as a APEX REST service
  • Custom_Path is a customizable URL Defined for your end-point.
@HttpPost, @HttpGet, @HttpDelete, @HttpPut, @HttpPatch
  • Method Level annotation.
  • Method level annotations to map HTTP method functionality.
So with-in a class tagged @RestResource, , we tag different methods as @HttpPost or @HttpGet …
That’s how when a call comes in to our service, Salesforce knows where to map the call to.
Within each methods, there are 3 main classes that matters.
RestContext class
RestRequest and RestResponse Class
  • Aptly named classes instantiated for each call to an APEX REST endpoint.
  • Bit.ly/RestRequest
  • Bit.ly/RestResponse
  • We end up with RestRequest Object and RestResponse Obj.
  • When using the service, we wont be using “RestResponse“, but we might use the “RestRequest
  • Both of these methods would be heavily used during TEST Coverage.
RestRequest:
  • This is where we go to get all the information about the request.
  • Provides access to all aspects of request.
  • Inbound Request are automatically deserialized into a RestRequest instance
  • Example:
    • Headers
    • httpMethod
    • Params
    • remoteAddress
    • requestBody –> We can desserialize it, if we want to look at anything.
    • requestURI –> we can see what is the Endpoint which was requested.
    • resourcePath
RestResponse:
  • This is the thing which is going to go back once the service is complete.
  • Provides access to all aspects of response
  • Example:
    • statusCode
    • responseBody –> we don’t need to do anything to create this,.
    • Headers
  • Method return value is automatically serialized into the responseBody.

WorkBench:

Its important how to build the Errors , if the request is going as expected.

The response are automatically de-serialized it for us by the platform.
Notice that the default response is JSON. If we want it in XML, we set the header to return back in XML.

XML Output:

VERSIONING of Services is important. This is because , we don’t need to affect the services, which are already in place.
The serialization not just extends to sObjects ,but also
  • Apex Primitives (excluding BLOB)
  • sObjects
  • Lists or Maps
  • User defined Types that contains member variable of types listed above.
    • This is BIG. We can define our own class and this would get de-serialized.

Operating on Resources and its Entities:
  • So far, we have been operating only under specific entities
    • V2/Accounts/1003
  • REST_Account_V3
    • Maintain existing record lookup via foreign key
      • /V3/accounts/1023 –>Allow the service to provide data for specific Account
    • Query String provide search capabilities
      • /v3/accounts?Name=United –> Allow to provide search Capabilities

We Get it, Whats Next?
This Table would over-simplify a bit.

Let’s Try POST on for Size
  • REST_AccountService_V4
    • Should feel familiar
    • Request Body is required for POST
    • Parameters map to method signature.
    • Same Error handling Principles apply.
  • Method Definition strictly defines what can be passed
    • Might be great for your use-case , might not.
    • If you need more flexibility.

  • Here the method Definition for “doPost” is a STRICT definition.
  • So, if we need to add “BillingState” for doPost, then the service would fail.
  • So, the above is one way to do it.
Several more flexible ways to allow Input:
  • REST_AccountServices_V5
    • Your POST(or PUT or PATCH) method can take sObjects
    • If you include a valid field, it will be de-serialized into sObject Instance.
  • REST_AccountService_V6
    • You could also take List<sObject>
  • REST_AccountService_V7
    • Or Even Wrapper Class
REST_AccountServices_V5: (Passing sObject as Parameter)

REST_AccountService_V7 (Using Wrapper Classes)

What’s Next?
  • PUT/PATCH and DELETE
    • They are very similar to POST
  • Writing Test Coverage
    • Set our testData Up
    • Start the Test
    • We are going to define our Request and Response
  • GitHub Repo
TEST Coverage Example:

Sunday 10 January 2016

APEX : Class ( Simple/Regular Vs Abstract Vs Virtual )

Before going into differences between these, understand regular, abstract, virtual methods :
Regular Method  : Has code body or code implementation  and cannot be overridden

Virtual Method    : Has code body or code implementation and can be overridden by extending class method using override keyword

Abstract Method : Doesn't have body or code implementation and can be overridden by extending class method using override keyword



Regular Class:
a) Can be constructed ( can create object ).
b) Can not be extended
c) Can have regular methods
d) Can have virtual methods
e) Can not have abstract methods

Virtual Class:
a) Can be constructed ( can create object ).
b) Can be extended
c) Can have regular methods
d) Can have virtual methods
e) Can not have abstract methods

Abstract Class:
a) Can not be constructed ( can not create object ).
b) Can be extended
c) Can have regular methods
d) Can have virtual methods
e) Can have abstract methods

Note:
i) Extending class can not reduce visibility of super method by overriding it.
ii)Extending class can not change return type of super method by overriding it.
iii)Extending can do method over loading e.g.

Super class has 
public void getName(){
return 'My Name'; 
}

and Extending class can have
public getName(String str){
return str; 
}

iv) class can't extend two classes but can extend one class (virtual/abstract) and implements multiple interfaces.