Friday, October 5, 2012

Salesforce REST API Folders and Documents

In a recent post I described how to retrieve a file stored in Salesforce using the REST API. In that post I showed how to retrieve a document using its internal ID number which really isn’t to useful in practice, it would be better to retrieve it by name. In this post I will show how to look at folder and file information in Salesforce. All the queries in this post can be executed using the code I showed in the Salesforce REST API Query post.
Let’s start by looking at folders. You can query for a list of folders by using this SOQL statement:

SELECT ID,Name,DeveloperName FROM folder

This will return a JSON response something like this:

{
  "totalSize" : 1,
  "done" : true,
  "records" : [ {
    "attributes" : {
      "type" : "Folder",
      "url" : "/services/data/v24.0/sobjects/Folder/00lE0000000zg7MIAQ"
    },
    "Id" : "00lE0000000zg7MIAQ",
    "Name" : "Test Folder",
    "DeveloperName" : "Test_Folder"
  } ]
}

In the response you will see a record for each Folder in your Salesforce instance with fields for the ID, the folder name, and the DeveloperName which is a unique name without any spaces.

Now that we have the folder ID we can query for all the documents in that folder.

SELECT ID, Name, DeveloperName FROM document where Folderid='00lE0000000zg7MIAQ'

which will return a response like this:

{
  "totalSize" : 1,
  "done" : true,
  "records" : [ {
    "attributes" : {
      "type" : "Document",
      "url" : "/services/data/v24.0/sobjects/Document/015E00000019TzdIAE"
    },
    "Id" : "015E00000019TzdIAE",
    "Name" : "Test in Folder",
    "DeveloperName" : "Test_in_Folder"
  } ]
}


Just like the folder query this one returns an Id, Name and DeveloperName for each document in the folder. If you want you can also remove the where clause from that query and it will return a list of all documents no matter what folder they are in.

You might think that you could do something like this in one query using a join, but although SOQL does support joins, they don’t work with folders and documents, so you have to do the two separate queries.

Besides Id,Name and DeveloperName there are some other useful fields you can retrieve for a document.

LastModifiedById – Internal ID of the user that last modified the document record.
LastModifiedDate – Date that the document record was last modified.
CreatedById – Internal ID of the user that created the document record.
CreatedByDate – Date the document record was created.
AuthorID – Internal ID of the user who is currently selected as the author of the document.
Type – The file extension of the document.
ContentType – The MIME type of the document.
Keywords – The keywords field in the document record.
Description – The description field in the document record.
IsInternalUseOnly – The boolean Internal Use Only field in the document record.

No comments: