When building a composite Force.com application, it is often necessary to dynamically generate the current Session Id and API Server URL from
within Visualforce and Apex. These parameters let the external application access the salesforce.com Web Services API if any callbacks are
required to query, insert, or update data. In the past this was often handled in the SControl's javascript using merge field syntax such as
{!API.Partner_Server_URL_140} and {!API.Session_ID}.

Below is some sample code illustrating how simple it is to set these 2 parameters in a Visualforce Page and set them in an Apex Controller.
This will allow you to pass those parameters in any external web service calls or in a URL redirect including them in the URL as query string

The sample uses a combination of <apex:ActionSupport> and <apex:param> to pass the two parameters to the
Apex Controller, myController, when a user clicks on the text "Click Here To Generate Session Id and Server URL".

Visualforce Page
<apex:page setup="true" controller="MyController" showHeader="false">

<apex:form >
<apex:outputpanel id="counter">
<apex:outputText value="Click Here To Generate Session Id and Server URL" />
<apex:actionSupport event="onclick" action="{!doLogin}" rerender="refreshId" status="counterStatus">
<apex:param name="sessionId" assignTo="{!apiSessionId}" value="{!$Api.Session_ID}" />
<apex:param name="serverURL" assignTo="{!apiServerURL}" value="{!$Api.Partner_Server_URL_140}" />
<apex:outputPanel id="refreshId">
<apex:outputText value="API Session Id: {!apiSessionId}"/><br></br>
<apex:outputText value="API Server URL: {!apiServerURL}"/><br></br>

Controller Apex Class
public class MyController {

public String apiSessionId {get;set;}
public String apiServerURL {get;set;}

public PageReference doLogin(){

System.debug('apiSessionId: ' + apiSessionId);
System.debug('apiServerURL: ' + apiServerURL);
return null;


Get the latest Salesforce Developer blog posts and podcast episodes via Slack or RSS.

Add to Slack Subscribe to RSS