[SalesForce] Dynamic SObject API Name from Object Label

Is there a way to fetch the Object API Name using the Dynamic Object label and Schema. The other way around i have done. But i need this way to get SF API Names to be sent through Rest.

I tried for Standard Case Object and its working fine, But I have a custom object called "TMC Info", Its API name is "Agency_Info__c"

But i want this value to be dynamically fetched.

Below is the code i have used and its working for standard object, but not working for custom object :

// If i give this value as 'Case' its working, but this value 'TMC Info' is showing error as Attempt to deference NULL
String myObj = 'TMC Info';  
Schema.DescribeSObjectResult describe = Schema.getGlobalDescribe().get(myObj).getDescribe();
system.debug(describe.getName());

i fetched all the object api name and label, and i find the custom object "TMC Info" and its api name getting returned :

for ( Schema.SObjectType o : Schema.getGlobalDescribe().values() )
{
    Schema.DescribeSObjectResult objResult = o.getDescribe();
    system.debug( 'Sobject: ' + objResult );
    system.debug( 'Sobject API Name: ' + objResult.getName() );
    system.debug( 'Sobject Label Name: ' + objResult.getLabel() );   
}

Here is the picture :

Debug log for All object api

Is there anything I'm missing here ?

Best Answer

The object label should never be used as an identifier of the Sobject on an external system, because the label is not unique. If you were to construct such a solution, it could have a significant chance of breaking in the future, should

  • An object's label be altered (a change that generally shouldn't cause code-level problems, and which an admin might not know would have this side effect).
  • Two objects have the same label (a situation that could be created simply by installing a managed package, not even requiring any explicit label changes by your administrator).

To avoid this high fragility, the external system must use the object's API name as its unique identifier. If the external system has a user-facing aspect, it could source the labels for the objects from Salesforce and display these to the user, and you could dynamically fetch the display names, or cache and regularly refresh them. However, the external system's internal data storage and communication over the UI API or other Salesforce APIs should use the object's API name.

In many cases, the label and API name for standard objects are the same. This is true for Case, as you've seen. However, it's not true for other standard objects or for custom objects. For example, the standard object with API name OpportunityLineItem has the label Opportunity Product.

Note that the keys in the Map returned by Schema.getGlobalDescribe() are the API names of the objects, not the labels. That's why your example works for Case, but not for a custom object.