Specializes In

Getting a Session ID in APEX using the Login Partner API Call.

Salesforce is great at allowing access to itself through the many possible APIs. The first step in most cases is to do a Login to the Partner or Enterprise APIs so that a session ID can be returned. Once you have this session ID you will be able to make subsequent API calls as needed.

But what if I want to log into another Salesforce instance or my current Salesforce instance so that the Salesforce APIs can be used? Maybe I want to log into a few of my sandboxes from my production org to collect data about how many rows of contacts exist in each sandbox. The first step before making such a query is to log into the other org or your current org to get the session ID. You could download the entire Partner API and then make modifications to the WSDL so that the ‘WSDL to APEX’ functionality can be used. For example, there are certain reserved words like ‘Update’ that need to be changed to something like ‘Update2’ before the WSDL can be imported. But even once it is imported there are so many extra function calls that you are never going to use. Let me show you how to log into Salesforce using the HTTP objects that APEX provides.

We need to construct the XML that will be sent in the SOAP message for logging in. The way that I like to see the XML structure is to build my API call in VB.NET, run the call and then capture the XML as it is sent with a tool like Fiddler at www.fiddler2.com. This fiddler Web Debugging Proxy will capture the XML that is both sent and received. You can then build that XML string yourself in APEX and send it the same way. Here is some code that does just this for calling the Partner API Login method.

if (true){ //Keep the setting on whether this is a production or sandbox in a custom object.
loginURL = 'https://test.salesforce.com/services/Soap/u/26.0';
}else{
loginURL = 'https://login.salesforce.com/services/Soap/u/26.0';
}

I hope that some of this code can kick-start some of your integration projects. You can now log into any Salesforce Org. To make any subsequent calls like doing a query or an insert just make those same calls in Java or .NET and intercept the XML using fiddler. Then you can build that same XML and then using the session ID it should be easy to make that next call.