Wednesday, January 29, 2014

Use force.com Rest API to upload documents or attachment

It took me hours and hours try use force.com Rest API to upload documents and attachments. It didn't help the developer guide only shows upload the document. I guess you are supposed to figure out how to add attachment. Anyway, here are the hoops I had to jump through.

Let's look at document first.

I follow this doc:
http://www.salesforce.com/us/developer/docs/api_rest/index_Left.htm#CSHID=dome_sobject_insert_update_blob.htm|StartTopic=Content%2Fdome_sobject_insert_update_blob.htm|SkinName=webhelp

Pay close attention to a couple of things:

the URL in the sample is: curl https://na1.salesforce.com/services/data/v23.0/sobjects/Document/ -H "Authorization:
Bearer token" -H "Content-Type: multipart/form-data; boundary=\"boundary_string\""
--data-binary @newdocument.json

* replace your own URL, yours won't be "na1"!
* the last part of the URL is "/Document/" for document. For attachment is "/Attachment/"
* @newdocument.json means the cURL will read in the file (pardon me, not a json guy)
* In the sample jason code, it shows "FolderId" : "00lJ0000000HzyY". Normally, with na1salesforce.com/xyz, xyz is the object ID. But for document folder, it looks like salesforce.com/015?fcf=00lJ0000000HzyY, use the last part after cfc=.
*use this text file to test your upload before you try binary file:

--boundary_string
Content-Disposition: form-data; name="entity_content";
Content-Type: application/json

{"Description":"Marketing brochure for Q1 2013","Keywords":"marketing,sales,update","FolderId":"00lJ0000000HzyY","Name":"Marketing Brochure Q1","Type":"text"}

--boundary_string
Content-Disposition: form-data; name="Body"; filename="fakefile.txt";
Content-Type: text/plain

This is the content of my fake file

--boundary_string--

* trick to create binary json file: create a header.txt (everything before "This is the content of the my fake file", and tail.txt (just the last line). Make sure newlines accounted for. Now run copy header.txt + test.pdf/b+tail.txt newdocument.json
notice there is "/b" after the binary file name, in this case, it's pdf. you need to update header to change to "PDF' where applicable, for example: Content-Type: application/pdf

Now let's move on to attachment:

You need to change two things:

1. the URL, last part needs be "/Attachment".
2. in the json property, i modified it to be {"Description":"Marketing brochure for Q1 2013","ParentId":"a00J0000006ntLCIAY","Name":"Marketing Brochure Q1"}. I removed "Keywords", "Type", replaced with "ParentId", this is the object ID to which you want to add the attachment to.

I'm sure there are other properties you can play with. That's quite enough for me for now.