Creating Files with the Salesforce REST API and Postman

In order to create a File on Salesforce, the object behind the scenes is actually three-fold:

  • ContentDocument containing metadata of the file
  • ContentVersion containing binary data of the file, child to the ContentDocument
  • (optional) ContentDocumentLink being the M:M between the ContentDocument and a record to which it’s linked

ContentDocument records cannot be created directly. When creating a ContentVersion record, if the ContentDocumentId is unspecified, the ContentDocument will be created behind the scenes.

The standard Salesforce REST API is a great way to interact with data on Salesforce from outside of the platform without any customization required. Creating ContentVersions are actually a little counter-intuitive, however.

I use Postman to quickly create REST payloads and headers. It’s a great, lightweight, fully featured, free tool.

When attempting to follow the instructions on the Developer Guide for inserting a ContentVersion, it calls for creating the payload as Content-Type multipart/form-data, with file metadata as Content-Type application/json and the binary file as its own Content-Type. Postman does support selecting a file, simply select the type as File in the right part of the Key. It doesn’t support the metadata as separate attributes, however. If the payload is constructed like this:

postman

the REST POST will respond with the following message

[
    {
        "message": "Multipart message must include a non-binary part",
        "errorCode": "INVALID_MULTIPART_REQUEST"
    }
]

There are two things you have to do. First, you have to specify the Content-Type of each part of the multipart payload. To do this, select the three dots and ensure Content-Type in the “Show Columns” section:

postman

Second, the metadata actually has to be enclosed within one key/value pair in Postman. In order to do this, create a part with Content-Type application/json, key entity_content, and value being a json object with your ContentVersion metatata. The following works:

postman

Hat tips:
Stackexchange
Joseph Thomaschaske and James M from the “Good Day, Sir!” slack channel

Bookmark the permalink.