[SalesForce] How to create a File (a la Lightning) and link it to a Case via REST API

In the Lightning UI if you attach a file to a Case it won't be created as an Attachment, rather as a File. I could not find anything about this in the REST API docs.

What I found just by try and error is that one must create a ContentBody, a ContentDocument, a ContentDocumentVersion and finally a ContentDocumentLink to link it to the Case. If this is really the way, how to upload the file in the first place? i.e. how to create a ContentBody? Again nothing related to this in the docs.

My assumption is that still a multi-part request with a Body part should work but haven't tried it yet. Any help would be appreciated

Best Answer

Follow these three steps to create a File and link it to your object.

Create a ContentVersion

Follow the docs to create a new version with a multipart request. Note that this will automatically create a ContentDocument but unfortunately does not return its id. What it returns is the id of the created ContentVersion which we call $CONTENT_VERSION_ID

Fetch id of the automatically created ContentDocument

Run the following SOQL query:

SELECT ContentDocumentId FROM ContentVersion WHERE Id = '$CONTENT_VERSION_ID'

It will return an id which we call $CONTENT_DOCUMENT_ID

Link ContentDocument to Object

Create a ContentDocumentLink object using the following json:

POST /sobjects/ContentDocumentLink

{ ContentDocumentId: $CONTENT_DOCUMENT_ID, LinkedEntityId: $SOBJECT_ID, ShareType: "V" }