Upload Document Using Composite API

Simplify Document Uploads with Salesforce's Composite API

Manually linking uploaded files to records in Salesforce typically requires a tedious chain of multiple HTTP requests. Salesforce’s Composite API solves this by letting you execute a series of actions in a single REST call, reducing network overhead and enforcing sequential logic.

Why Use the Composite API for Document Management?

  • Reduced API Calls: Create records, upload files, and link them together in one request.
  • Reference Dependencies: Use the ID of a record created in Step 1 immediately in Step 2.
  • All-or-None Execution: Roll back the entire operation if a single step fails (optional but recommended).

The Implementation Workflow

Uploading a document and attaching it to a record (like a Case) requires three primary steps handled sequentially within the composite request body:

  1. Create the Parent Record: Generate the Case (or any standard/custom object).
  2. Upload the File: Insert a ContentVersion record containing your base64 encoded document data.
  3. Link the Document: Retrieve the auto-generated IDs to create a ContentDocumentLink, binding the file directly to the parent record.

Code Example

{
  "allOrNone": true,
  "compositeRequest": [
    {
      "method": "POST",
      "url": "/services/data/v51.0/sobjects/Case",
      "referenceId": "CaseObj",
      "body": {
        "Subject": "App Crash Investigation",
        "Status": "New"
      }
    },
    {
      "method": "POST",
      "url": "/services/data/v51.0/sobjects/ContentVersion",
      "referenceId": "ContentVersionObj",
      "body": {
        "Title": "Error_Log_Screenshot",
        "PathOnClient": "error_log.png",
        "VersionData": "mS0wLWg...[Your Base64 Encoded File String]..."
      }
    },
    {
      "method": "GET",
      "url": "/services/data/v51.0/sobjects/ContentVersion/@{ContentVersionObj.id}",
      "referenceId": "ContentVersionObjGet"
    },
    {
      "method": "POST",
      "url": "/services/data/v51.0/sobjects/ContentDocumentLink",
      "referenceId": "ContentDocumentLinkObj",
      "body": {
        "LinkedEntityId": "@{CaseObj.id}",
        "ContentDocumentId": "@{ContentVersionObjGet.ContentDocumentId}",
        "ShareType": "V"
      }
    }
  ]
}

Handling the Response

  • Success (200 OK): Inspect the JSON response array. Each object will map back to your referenceId, providing the final Salesforce IDs for confirmation.
  • Error Handling: If allOrNone is set to true, any failure (e.g., a missing mandatory field or corrupted base64 string) rolls back the entire batch, keeping your Salesforce data clean.

Comments

Popular posts from this blog

Communicating between Independent LWC in Omniscript

Server-Side Document Generation

Mastering the Matrix: Top 10 Advanced Salesforce Integration Interview Questions