How to determine your org type via apex code

Sometimes we want to use different values among production and sandboxes, one typical scenario is that we'd better use test endpoints instead of production endpoints because we don't want to mess up with the data in the production.

Here comes the question: how can we determine current org type in the apex code?

After Summer 14', the Organization object has a new read-only field: IsSandbox

release note

We can take advantage of that field to achieve our goal.

public class Utility  
{
    public static Boolean isSandbox
    {
        get
        {
            return [select IsSandbox from Organization limit 1].IsSandbox;
        }
    }

    public static String ServiceEndpoint
    {
        get
        {
            if(isSandbox)
            {
                return 'https://test.api.com';
            }
            else
            {
                return 'https://production.api.com';
            }
        }
    }
}

We can use Utility.isSandbox to determine current org type, use Utility.ServiceEndpoint to get the service endpoint in both production and sandbox.

Adam Wu

Weeks of programing can save you hours of planning