Salesforce CORS JSONP

In this blog, I am going to explain how to solve CORS in Salesforce  by using JSONP( JSON Padding ) 

What is CORS?

CORS introduces a standard mechanism that can be used by all browsers for implementing cross-domain requests. The spec defines a set of headers that allow the browser and server to communicate about which requests are (and are not) allowed.Cross-Origin Resource Sharing (CORS) allows us to use Web applications within browsers when domains aren’t the same. For example, a site with domain wants to execute AJAX requests to a Web application with the domain using HTTP.
                        For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and Fetch follow the same-origin policy. So, a web application using or XMLHttpRequest Fetch could only make HTTP requests to its own domain.

               The Cross-Origin Resource Sharing standard works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser.  Additionally, for HTTP request methods that can cause side-effects on server’s data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers “preflight” the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon “approval” from the server, sending the actual request with the actual HTTP request method. Servers can also notify clients whether “credentials” (including Cookies and HTTP Authentication data) should be sent with requests.

What is JSONP?

JSONP is JSON Padding is technology that enables Sharing of data bypassing Same-origin policy. The policy disallows running JavaScript to read media DOM elements or XHR data fetched from outside the page’s origin In JSONP  a server must reply with a response that includes the JSONP function. JSONP does not work with JSON-formatted results. The JSONP function invocation that gets sent back, and the payload that the function receives, must be agreed upon by the client and server.

For Examples in this script, parseResponse is the function which will return as part of the script invocation

In this example, the received payload would be: parseResponse({“Name”: “Foo”, “Id”: 1234, “Rank”: 7}); because Javascript called via the tagscript isn’t subject to the browser’s same-origin policythe response will simply be executed in the browser with our parseResponse function.

Breaking it all down

The core elements of JSONP, then, are as such:

  1. A callback function defined on your site.
  2. A request to the remote API via <script> tag:
    • Includes a special param providing the name of your callback function
  3. The response:
    • Is just Javascript
    • That consists of:
      • A function call, the name of which you specified in the request
      • With the argument being the JSON data of interest
    • Gets executed immediately, as if it were called from your own domain

Let’s test now:-

Create a visualforce page with the following code. 

<apex:page showHeader="false" standardStylesheets="false">
    <script type = "text/javascript" language = "javascript">
    $(document).ready(function() {
            $.getJSON('', function(jd) {
                $('#stage').html('<p> Name: ' + jd.description + '</p>');
        <p>Simple JSON File to show the Demo .</p>
        <div id = "stage" style = "background-color:#cc0;">
            Data Will be loaded 
        <input type = "button" id = "btn" value = "Load Data" />

Now after loading the page, go to console you will see an error message as shown below.

Now Replace the above code with the below code which is having JSONP logic 

<apex:page showHeader="false" standardStylesheets="false">
    <script type = "text/javascript" language = "javascript">
    $(document).ready(function() {
            var script=document.createElement('script');
    var processJSON = function (json) {
        for (var item in json.items) {
        <div id = "stage" style = "background-color:#cc0;">
            Data Will be loaded 
        <input type = "button" id = "btn" value = "Load Data" />

Now if you can go and see the console, you will not see any error message.


Salesforce REST API Composite Resources

In this blog, I am going to explain salesforce rest API composite resource which is designed to reduce the number of round trips to the server.  A composite API is a sequence of tasks that run synchronously and  Composite API is built by combing the existing API functions that can perform the multiple tasks in the single call. Salesforce composite resources contain Composite, Tree, batch resources.

A composite API may be used :

  • To speed up the execution of a sequence of tasks instead of making separate calls
  • To compose an API by creating a sequence of web services
  • Composite API run synchronously

Salesforce provides three composite resources namely composite, batch, tree
composite/: Executes a series of REST API requests in a single call. You can use the output of one request as the input to a subsequent request.
composite/batch/: Execute a set of subrequests in a single request. Subrequests are executed independently and information can’t be passed between subrequest calls.
composite/tree/: Creates one or more sObject trees with root records of the specified type. An sObject tree is a collection of nested, parent-child records with a single root record.

Composite Resource 
Composite Resource Executes a series of REST API requests in a single call. You can use the output of one request as the input to a subsequent request. .The requests in a composite call are called subrequests. All subrequests are executed in the context of the same user. In a subrequest’s body, you specify a reference ID that maps to the subrequest’s response. You can then refer to the ID in the URL or body fields of later subrequests by using a JavaScript-like reference notation. Let us consider you wanted to create a work order and work order items on the same call.The following examples contain two subqueries where the first request creates a work order and for the second request, we will pass create a work order items where we will pass the referenceId on the first request.


Salesforce REST API Recently Viewed Items

In this blog, I am going to explain how to use the salesforce rest API recently viewed the resource. You can able to access the recently viewed data by using even SOQL querying on the RecentlyViewed object or by Using REST API or by using LastViewedDate field with SOQL where clause.A record is considered viewed when the user sees the details associated with it, but not when the user sees it in a list with other records.Use this query in your code to retrieve a list of all the records that were recently viewed.

SELECT Id, Name FROM RecentlyViewed

Salesforce stores information about record views in the interface and uses it to generate a list of recently viewed and referenced records, such as in the sidebar and for the auto-complete options in search.

You can get the Recently Viewed Records by using /services/data/v41.0/recent rest resources.

 Below is the apex class
public class RecentlyViewController {
    public static List<RecenlyViewWrapper> getRecentItems(){
        List<RecenlyViewWrapper> warpperlist = new List<RecenlyViewWrapper>() ; 
        Http h = new Http();
        HttpRequest httpReq = new HttpRequest();
        HttpResponse res = h.send(httpReq);
        List<RecenlyViewWrapper> recentItemsList =
            (List<RecenlyViewWrapper>)JSON.deserialize(res.getBody(), List<RecenlyViewWrapper>.class);
        return recentItemsList ;
    public class RecenlyViewWrapper{
        public String Id {get; set;}
        public String Name {get; set;}

Here the below Lightning Component.

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes" access="global" controller="RecentlyViewController">
    <aura:attribute name="recentItems" type="List"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <table class="slds-table slds-table--bordered">
            <aura:iteration items="{!v.recentItems}" var="recentItem">
                        <ui:outputURL value="{!recentItem.Id}" label="{!recentItem.Name}">  </ui:outputURL>

Component Controller

    doInit : function(component, event, helper) {
    } , 

Component helper

    getRecentItems : function(component) {
        var action = component.get("c.getRecentItems");
        action.setCallback(this, function(a) {
            component.set("v.recentItems", a.getReturnValue());