Skip to main content

Upload Documents using REST API in Salesforce Apex

In plain words: You can upload documents programmatically in Salesforce using Apex by constructing an HTTP POST request targeting the Salesforce REST API. This method allows you to send base64-encoded files along with required parameters like folder IDs or document names directly through code.

In Salesforce, Apex allows you to extend platform capabilities beyond the standard UI. A frequent requirement in enterprise integrations is uploading files and documents programmatically using REST endpoints. This guide demonstrates how to configure API access and build a dedicated Apex class to upload files securely.

Upload document using rest api from apex class salesforce

Prerequisites

Before implementing the Apex code, ensure you have configured the following:

  • A Salesforce Developer Edition or Sandbox environment.
  • Salesforce API credentials with sufficient permissions (e.g., Modify All Data or Create Document access).
  • Fundamental knowledge of Salesforce Apex and RESTful HTTP callouts.

Step 1: Setting Up REST API Integration

To prepare your Salesforce environment for handling REST API calls, perform the following administrative setup:

  • Log in to your Salesforce Developer Edition or Sandbox org.
  • Click the Gear icon in the top-right corner and navigate to Setup.
  • In the Quick Find box, type API and select API Integrations (or Connected Apps depending on your OAuth setup).
  • Ensure REST API access is active.
  • Generate or retrieve your OAuth security token and client credentials for callout authorization.

Step 2: Writing the Apex Document Uploader Class

Next, create an Apex class that handles the payload construction, sets the headers, and submits the HTTP request.

  • In Setup, search for Apex Classes and click New.
  • Name your class DocumentUploader and paste the code below:
public class DocumentUploader {
    
    // Replace with your actual Salesforce instance URL
    private static final String SALESFORCE_INSTANCE_URL = 'https://your-instance-url.salesforce.com';
    
    // Replace with your actual Salesforce access token
    private static final String ACCESS_TOKEN = 'your-access-token';
    
    // Replace with your document object API name (e.g., 'Document' or 'ContentVersion')
    private static final String DOCUMENT_OBJECT_API_NAME = 'Document';
    
    // Replace with the folder ID where you want to upload the document
    private static final String FOLDER_ID = 'your-folder-id';
    
    public static void uploadDocument(String documentName, String base64Data) {
        HttpRequest request = new HttpRequest();
        request.setEndpoint(SALESFORCE_INSTANCE_URL + '/services/data/v52.0/sobjects/' + DOCUMENT_OBJECT_API_NAME + '/');
        request.setMethod('POST');
        
        String boundary = '----------------------------741e90d31eff';
        String header = '--' + boundary + '\r\nContent-Disposition: form-data; name="entity_attachment";' +
                        ' filename="' + documentName + '"\r\nContent-Type: application/octet-stream\r\n\r\n';
        String footer = '\r\n--' + boundary + '--\r\n';
        
        String body = header + base64Data + footer;
        
        request.setHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
        request.setHeader('Authorization', 'Bearer ' + ACCESS_TOKEN);
        request.setHeader('Content-Length', String.valueOf(body.length()));
        
        request.setBody(body);
        
        HttpResponse response = new Http().send(request);
        
        if (response.getStatusCode() == 201) {
            System.debug('Document uploaded successfully.');
        } else {
            System.debug('Error uploading document: ' + response.getBody());
        }
    }
}
Implementation Details:
  • Replace SALESFORCE_INSTANCE_URL with your domain (e.g., https://my-domain.my.salesforce.com).
  • Replace ACCESS_TOKEN with a valid OAuth 2.0 access token generated via your integration flow.
  • Replace DOCUMENT_OBJECT_API_NAME with ContentVersion if you are working with Salesforce Files instead of classic Documents.
  • Replace FOLDER_ID with your target workspace or folder ID.

Executing the Code

To trigger the upload, invoke the uploadDocument method from an Execute Anonymous window or another Apex controller:

String documentName = 'MyDocument.pdf';
String base64Data = 'JVBERi0xLjQK...'; // Replace with valid base64 string
DocumentUploader.uploadDocument(documentName, base64Data);
Warning: String concatenation for large base64 files can quickly exceed Apex governor limits for heap size (6 MB for synchronous, 12 MB for asynchronous execution). For files larger than a few megabytes, use native SObject insertion (ContentVersion) or blob-based HTTP callouts instead of raw string bodies.
Key Summary Card:
  • Protocol: REST API over HTTPS
  • HTTP Method: POST
  • Content Type: multipart/form-data
  • Success Response: HTTP 201 Created

By leveraging custom HTTP callouts in Apex, you can automate document creation and file distribution processes across your Salesforce ecosystem smoothly.