Wednesday, January 29, 2014

Use Rest API to upload documents or attachment

It took me hours and hours try use 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:|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 -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, xyz is the object ID. But for document folder, it looks like, use the last part after cfc=.
*use this text file to test your upload before you try binary file:

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"}

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

This is the content of my fake file


* 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.