Rest API

Insert ContentVersion By Rest API | The Salesforce Developer Guide

In this document, we are going to insert a contentVersion from a Salesforce Source org to a particular sObject of target Salesforce org by using Rest API and web resources in Salesforce. Before starting, we have to understand the Content Version which is the standard object in Salesforce. Content Version is a child of Content Document and it has a versionData field that holds the body of any uploaded document in the Salesforce. Whenever we upload a document in Salesforce its Content Version is automatically created.

There are multiple steps to complete this process of integration which are given as follows:

STEP 1: Create a connect app in your target Org where you want to send a Content Document and insert it. After creating a connected app, we get Client_Secrete, Client_Id, UserID, and Password of the target Org for the callOut from the source Org.

dont miss out iconDon't forget to check out: Salesforce Platform API Versions 21.0 thru 30.0

STEP 2: We have to create a RestAPI class in your Source org where we provide all necessary values like Client_Secrete, Client_Id, UserID and Password to get Access Token of the second Org. There is my RestApi class which is given as follows:

public class SendAttachmentByRestAPI {
    private final String clientId =   '3MVG9n_HvETGhr3BCK8XntxzLOntIoGgoZcZuV3DniFPCItOlhpeB8drfSpbyjrb2x27aqKM.5mvoMRydyBKo';
    private final String clientSecret = '50BC02950F0200AC55A9420C60D0FAE85753A0C64672CE9485DE5C713D6BD61B';
    private final String username = '[email protected]';
    private final String password = 'Algo@123rSk8lzZnqsdya4QuPmTIi9oZ';
    public class deserializeResponse {
        public String id;
        public String access_token;
        public string instance_url;
    }    
    public String getAccessToken (){
        String reqbody = 'grant_type=password&client_id='
            +clientId+'&client_secret='
            +clientSecret+'&username='
            +username+'&password='+password;        
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://adyadav42-dev-ed.my.salesforce.com/services/oauth2/token');        
        req.setMethod('POST');
        req.setBody(reqbody);
        //req.setHeader('Authorization', 'OAuth '+UserInfo.getSessionId());
        HttpResponse res = h.send(req);
        deserializeResponse response = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
        system.debug('@@@@access_token@@'+response );
        return response.access_token;
    }
    public static void sendAttachement(){
        //get Access Tocken
        SendAttachmentByRestAPI accessTk = new SendAttachmentByRestAPI();
        String accessToken;
        accessToken = accessTk.getAccessToken();
        System.debug('accessToken==='+accessToken);        
        String attchParentId;
        String attchBody;
        string reqBody;        
        ContentVersion conDoc =  [SELECT Id, Title, VersionData FROM ContentVersion where ID= '0682x000004Ki1CAAS'];
        system.debug('conDoc==='+conDoc);
        //get ContentVersion body
        String bodyEncoded = EncodingUtil.base64Encode(conDoc.VersionData);
        Id accID = '0012w00000LR4JjAAL';        
        if(accessToken != Null){
            Http h = new Http();
            HttpRequest req = new HttpRequest();
            req.setEndpoint('https://adyadav42-dev-ed.my.salesforce.com/services/apexrest/addi/DocumentUploadBinary?accID='+accID+'&contentType=application/JSON&name=DocUploads.pdf');             
            req.setMethod('POST');
            system.debug('bodyEncoded===='+bodyEncoded);
            req.setBody('');
            req.setHeader('Authorization','Bearer '  +accessToken);
            req.setHeader('Content-Type','application/json');
            //req.setHeader('accept','application/json');
            System.debug('END-POINT===='+req.getEndpoint());
            HttpResponse res = h.send(req);            
        } 
    }    
}

There are two methods in my RestApi class where the first one is to get Access Token and the other is for sending the request to the web service class.

dont miss out iconCheck out another amazing blog by Aditya here: TriggerFactory in Salesforce Apex | The Developer Guide

STEP 3: This is the final step in which we create a WebService Class of @httpPost method in the target Org where we get data from the target org after the callOut and Insert it into the Org. Here is my WebService class that is given as follows: 

@RestResource(UrlMapping='/DocumentUploadBinary/*')
global class DocumentUploadBinary {
    @httpPost
    global static void uploadDocument(){
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        Id accID = req.params.get('accID');
        String contentType = req.params.get('contentType');
        String name = req.params.get('name');        
        //insert contentVersion
        contentVersion cVersion = new contentVersion();
        cVersion.PathOnClient = name;
        cVersion.title = name;
        cVersion.versionData = req.requestBody;
        insert cVersion;        
        ID conDocument = [Select ContentDocumentID from ContentVersion where ID=:cVersion.ID].ContentDocumentID;
        //insert ContentDocumentLink
        ContentDocumentLink conDocLink = new ContentDocumentLink();
        conDocLink.LinkedEntityId = accID;
        conDocLink.ContentDocumentId = conDocument;
        insert conDocLink;       
        RestContext.response.addHeader('content-Type','application/json');
        //RestContext.response.responseBody = Blob.valueOf(generateJSON('SUCCESS', conDocument,'' ));        
    }
}

 

Responses

Popular Salesforce Blogs