[SalesForce] Create and Link Document to multiple records using rest api

From the docs I've successfully been able to create a document in Salesforce using Inserting a New Document. I'd like to be able to link this document to multiple cases. From what I understand, it appears I need to use ContentDocument and ContentDocumentLink objects to achieve this.

How can this be achieved with the rest api? I see they have an example for how to create a ContentVersion in the docs, but they don't explain how to create a ContentDocument and get its Id to associate it to the ContentVersion

Best Answer

ContentDocument is not directly created - if you submit a ContentVersion without setting ContentDocumentId, it will create a new ContentDocument. You won't get the ContentDocument's Id in the response, so you'd need to retrieve or query the new ContentVersion to get the ContentDocument's Id for creating ContentDocumentLink records.

But, when creating a new ContentDocument in this way, you can also create an initial ContentDocumentLink by way of the FirstPublishLocationId field. From the Object Reference:

Setting FirstPublishLocationId allows you to create a file and share it with an initial record/group in a single transaction, and have the option to create more links to share the file with other records or groups later. When a file is created, it’s automatically linked to the record, and PublishStatus will change to Public from Pending/Personal.

This field is only set the first time a version is published via the API. FirstPublishLocationId can’t be set to another ID when a new content version is inserted.