As of API Version 33.0
, you can query CreatedBy
information via the Tooling API
. Queries including this field and using API Version 32.0
or below will fail.
SELECT CreatedById, CreatedBy.Name, DeveloperName FROM CustomObject

And since you asked how to do it via Apex
, you can hit the Tooling API
from Apex
as follows:
public static Map<SObjectType, Id> getCustomObjectCreatedBy()
{
String query = EncodingUtil.urlEncode(
'SELECT CreatedById, DeveloperName FROM CustomObject', 'UTF-8'
);
String endpoint = URL.getSalesforceBaseUrl().toExternalForm() +
'/services/data/v33.0/tooling/query?q=' + query;
HttpRequest request = new HttpRequest();
request.setMethod('GET');
request.setEndpoint(endpoint);
request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
request.setHeader('Content-Type', 'application/json');
String response = new Http().send(request).getBody();
Map<String, Object> payload = (Map<String, Object>)JSON.deserializeUntyped(response);
Map<String, SObjectType> sObjects = Schema.getGlobalDescribe();
Map<SObjectType, Id> output = new Map<SObjectType, Id>();
for (Object data : (List<Object>)payload.get('records'))
{
Map<String, Object> record = (Map<String, Object>)data;
String developerName = (String)record.get('DeveloperName');
String createdById = (String)record.get('CreatedById');
output.put(sObjects.get(developerName), createdById);
}
return output;
}
I cached the global describe because it makes this snippet run about 7x faster in my sandbox. It's still not exactly fast...This snippet takes about a half second to run.