Integrating with the Platform

Abstract provides a number of integration points ranging from off-the-shelf native ERP connectors to web services, email, syndication feeds and HTTP-based REST callouts. The platform also supports several APIs, including the SOAP and REST APIs, providing the basis for integration with other languages such as Java, .NET, Ruby, Objective-C and PHP.

This article provides an overview of the fundamental developer integration points available on the platform. After reading this article you will be aware of approaches you could take, and have enough pointers to more in-depth material to implement your integration.

An Integration Taxonomy

There are a number of integration points on the platform. From a developer perspective, you can get your hands dirty and invoke web services from the platform, or expose classes on the platform as web service end-points. You can also interact with external HTTP end-points, react to incoming email messages, and have automated outbound messages sent when certain events occur.

With a slightly higher degree of sophistication, you can use the SOAP and REST APIs. They provide direct access to data within your organization. Using these APIs, you can create a client that integrates with from your language of choice. A targeted REST API is also available for accessing Chatter data.

Toolkits that wrap around this API provide utility classes that make this integration even easier for a range of languages, including Java, .NET, PHP, Objective C, Ruby and Adobe Flex.

This article is primarily concerned with these foundational integration points. However, we also provide a summary of other integrations that can be purchased or installed: for example, the platform has a number of native ERP connectors for connecting to other platforms such as Oracle and SAP, as well as a host of integration applications available on AppExchange.

Before investigating the details of the integration methods, its worth categorizing them. Often you will choose an integration method based on your needs and goals. Here are some primary integration patterns and how they can be implemented on the platform. The rest of the article examines these integration points in more details:

Foundational Platform Integration Points

The following sections examine the more fundamental integration building blocks:

  • Creating and exposing web services using the Apex programming language
  • Invoking external web services from Apex
  • Outbound messaging for invoking external web services when data changes
  • HTTP and REST integration
  • Email integration for inbound and outbound messaging
  • The SOAP APIs and associated toolkits, such as the Mobile SDK, AJAX Toolkit, Java, .NET, PHP and Adobe Flex integrations.
  • Syndication feeds via Sites

The following sections look at each of these in turn.

Inbound: Hosting Web Services with the Apex Web Services

The Web services support in Apex provides a way for you to invoke business logic on the platform from some external system.

Apex is a strongly-typed programming language that executes on the platform. Apex is used to add business logic to applications, to program controllers in the Visualforce user interface layer, and to write database triggers. For a description of Apex, see An Introduction to Apex Code.

Apex class methods can easily be exposed as SOAP-based web service calls, allowing them to be called from external applications as the basis of an integration. The following code exposes a method as a web service. When invoked, the web service will create and persist a new Contact sObject based on incoming parameters:

global class MyWebService { 
  webservice static Id makeContact(String lastName, Account a){ 
    Contact c= new Contact(lastName= 'Weissman',AccountId = a.Id); 
    insert c; 

The webservice keyword marks the method as a web service, and the global access modifier declares that the class is visible to all Apex code, everywhere. All classes defining these types of web services are required to be annotated like this.

The web service will be immediately available on the platform. To call it, you’ll simply need the automatically generated WSDL for the service, which can be found by navigating to the class using the Builder environment, clicking on the name of the class and hitting "Generate WSDL". You can then feed this into your language of choice, and call into your service on the platform.

The platform seamlessly handles a number of tasks automatically for you. It hosts the web service, handles the argument and return value conversions, generates the WSDL and so on. All you have to do is write the business logic that will be called when the web service is invoked. For full documentation on creating and exposing your own web services, see the Apex Language Reference.

You can also create inbound Apex REST web services.

Outbound: SOAP Services for Invoking External Web Services

The SOAP Service support within Apex Code allows synchronous and asynchronous callouts to an existing SOAP-based web service from within Apex. It works by consuming a WSDL description of the web service and automatically generating Apex code for the WSDL, including all stub and type classes.

As most of the process is automated, there is very little to describe! To get started, simply choose "Setup", "Apex Classes" then "Generate from WSDL" when logged in. You will be prompted for a WSDL document. On parsing the WSDL, the platform generates a default class name for each namespace in the WSDL document, and reports any errors (for example, if the WSDL contains an unsupported schema type).

Once the WSDL has been successfully parsed, the Apex classes can be generated. These classes automatically handle the SOAP to Apex data type conversions and the actual invocation.

Here is a snippet from an Apex class generated from a WSDL document that described a phone lookup service:

public myWS.PhoneResult LookupPhone(String phone) {
  myWS.LookupPhone_element request_x = new myWS.LookupPhone_element();
  myWS.LookupPhoneResponse_element response_x; = phone;
  Map<String, myWS.LookupPhoneResponse_element> response_map_x = 
     new Map<String, myWS.LookupPhoneResponse_element>();
  response_map_x.put('response_x', response_x);
    new String[]{endpoint_x,
  response_x = response_map_x.get('response_x');
  return response_x.LookupPhoneResult;

Of course, you don’t usually need to look at, or modify, these generated innards. Instead, all you have to do to invoke the web service is simply make a call to the LookupPhone method on the class—the platform handles all the hard work for you.

The use case for these SOAP services is similar to that of outbound messaging. However, instead of the platform dictating what the end point should look like, here you can specify the WSDL yourself.

Apex methods that invoke these web services may be annotated with the @future annotation. When this is done, the web service callout is made asynchronously—the callout is queued on the platform, and this queue can be monitored by navigating to the Setup -> Monitoring -> Apex Jobs page.

Outbound: Outbound Messaging

The Platform provides an outbound messaging system that lets you configure the platform to send SOAP-based messages to a web service endpoint on the internet. These messages are typically triggered by workflow rules on persisted objects. Although outbound messaging is asynchronous (each SOAP message can contain up to 100 notifications of changes), it also allows easy callbacks to the platform using the Soap API, as outbound messages contain the enterprise/partner endpoint URLs, as well a session ID token.

The outbound messaging service also features a retry mechanism on failed outbound messages, a retry system (it retries for 24 hours), a dead letter queue and a monitor (Setup -> Monitoring -> Outbound Messages).

It also provides many mechanisms that support security: HTTP/S and X.509 certificates provide the bulk of the security. You can also verify the IP address of the outbound messages to ensure that they come from servers, and the payload includes your organization ID, which you can verify.

The following figure summarizes the actions of the outbound messaging service.

Crl integration outbound.jpg

Setting up outbound messaging is a three step process:

  1. Set up the workflow rules and approval processes.
  2. Set up the outbound message workflow action that will fire when the workflow rules fire..
  3. Download the generated WSDL
  4. Use your language of choice to implement the web service endpoint that will receive the outbound messages.

The first three steps are carried out using the declarative environment provided under Setup in the user interface. For example, say that you have a Contact sObject. Using the workflow system, you can define an evaluation criteria of "Every time a record is created or edited" and bind the evaluation with an outbound message action, ensuring that an outbound message is sent whenever the criteria evaluates to true.

To set up this outbound message, simply go to Setup->Workflow & Approvals->Workflow Rules->New Rule. Select the Contact object, give the rule a name such as "ServerPingChange", set up some evaluation criteria (say "Every time a record is created or edited") and a Rule Criteria (for example "Formula evaluates to true" and have a formula of "true"). Hit "Save and Next" and "Done". That’s step 1.

For step 2, hit "Edit" under "Workflow Actions" for the workflow rule you just created, then "Add" and "Outbound Message". Give it a name and select your destination server for the endpoint address. You can then select which fields you want to send along in the message.

For step 3, look for the "Click for WSDL" button to download the WSDL file - this defines what your SOAP server endpoint needs to look like. You’ll want to activate your workflow rule now (hit "Activate" on the rule), and set up your security in Security Controls/Remote Sites to ensure that your remote server has access to

Now whenever you add/modify a contact, a SOAP message will be sent to the endpoint.

The following figure shows a configuration screen for such an outbound message:

Crl integration outbound setup.jpg

As you can see, it fires a message to an end-point address on your own server, and there are two workflow rules that can fire the message (outbound messages can be shared). You can track the status of outbound messages from the Setup->Monitoring->Outbound Messages page.

Note that this feature can be established without writing a line of code, it’s declarative. In addition, the platform dictates the structure of the end point. In other words, you have to use the generated WSDL to establish the end point. In contrast, the Apex SOAP Services let you invoke a web service end point of an existing service.

Outbound messaging is a powerful and easy way to communicate data changes in persisted objects to external web services. For detailed instructions on setting up an outbound message, see the SOAP API Developer's Guide.

Outbound: HTTP to invoke external REST services

The Apex language also provides a way to make HTTP calls. There are three classes primarily used to make these types of requests:

  • The Http class is used to initiate HTTP requests and responses.
  • The HttpRequest class is used to create GET, PUT, POST and DELETE requests, manipulate request headers, configure timeouts and more.
  • The HttpResponse class is used to handle HTTP responses, including determining HTTP response codes, response headers and content in the response body.

In addition, the EncodingUtil class contains useful encoding utilities.

Here’s a simple example. When the getContent() method is called with a URL, it will perform a GET on that web page, returning the body to the caller:

public class HttpCalloutSample { 
  //Pass in the endpoint to be used 
  public String getContent(String url){ 

  Http h=new Http(); 
  //Instantiate a new HTTP request,specify the method (GET) as well as the endpoint 
  HttpRequest req= new HttpRequest(); 

  //Send the request, andreturn a response 
  HttpResponse res = h.send(req); 
  return res.getBody(); 

This HTTP framework lies at the heart of many REST-based integrations. The Toolkit for Google Data APIs is a good example of this. The Toolkit utilizes the HTTP callouts to build an interface to the REST-based Google Data APIs. The full source code for the toolkit is available, and provides a good starting point for building your own REST-based services.

Refer to the Apex Language Reference for more information on the HTTP classes.

Inbound and Outbound: Email

Email is an important aspect of our online lives, and the platform provides a way to access inbound and outbound email functionality for integration. supports both outbound email messaging (sending emails to recipients), and inbound email handling (reacting to emails that are sent to the platform).

Outbound Email Messaging

For outbound email, the primary Apex classes to use are SingleEmailMessage, MassEmailMessage and Messaging. These classes let you send either an email to a single recipient, or a number of recipients. These emails can contain data, can be text- or HTML-base, and carry optional attachments.

Here’s a simple example:

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
String[] toAddresses = new String[]{'[email protected]'}; 
mail.setReplyTo('[email protected]'); 
mail.setSenderDisplayName('ACME Support'); 
mail.setSubject('Your wish');
mail.setPlainTextBody('It is done'); 
Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});

The classes are pretty straightforward and intuitive to use.

Inbound Email Handling

For inbound email, Apex Email Services can be used. Email services are automated processes that use Apex classes to process the contents, headers, and attachments of inbound email. For example, you can create an email service that automatically creates contact records based on contact information in messages. You can associate each email service with one or more platform-generated email addresses to which users can send messages for processing.

The heart of inbound email processing lies in an implementation of the Messaging.InboundEmailHandler interface. When configured, a method in an instance of this class will be invoked for each incoming email, allowing you to build your integration around the information in that email.

Here’s a simple implementation:

global class HandleWhims implements Messaging.InboundEmailHandler { 
  global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, 
  Messaging.InboundEnvelope env) { 
    Messaging.InboundEmailResult result= newMessaging.InboundEmailResult(); 
    System.debug('from email address:' + email.fromAddress);
    System.debug('email body:' + email.plainTextBody);
    System.debug('email subject:' + email.subject);  
    return result;

Once the class is created, use Setup->Develop->Email Services to establish an email address that maps to the class.

Refer to An Introduction To Email Services on and the Apex Language Reference for documentation on the Email classes.

Outbound: Sites Syndication Feeds Sites lets you create public websites and applications that run natively on the platform.

The pages on these public web sites can also contain dynamic syndication feeds. No coding is necessary to create the feeds. To create a feed, navigate to Setup -> Develop -> Sites, select a site, enable feeds, and then fill in the syndication feed form. This form requires a query (for example SELECT Id, Name FROM Account), a cache time out, and a simple mapping description which maps data values retrieved from the query, to feed elements (such as titles and descriptions). The platform will then automatically generate the feed for you, and you can distribute the feed for integration purposes.


There are two fundamental APIs for accessing data on from an external system:

  • The SOAP API is an API that provides you with direct access to your data and logic. This allows you to create integrations on your platform of choice, wherever you can create SOAP web service clients. The API follows the SOAP 1.1, WSDL 1.1 and WS-Basic Profile 1.1 specifications.
  • The REST API provides a REST-based web API for direct access to your data. It provides both XML and JSON output formats, and supports OAuth for authentication - particularly handy if creating clients for mobile platforms.

These APIs are fundamental integration points. They provide direct access to data within your application (organization), allowing you to query, create, delete and modify these data. They also provide calls to dynamically access metadata about a persisted data item (sObject). For example, a query can determine which fields are available in an sObject, and what the field types are. Finally, you can also use the APIs to perform utility calls, such as changing a user’s password, retrieving the server’s time stamp or sending an email.


The REST API makes provides OAuth 2.0 support for authentication, and XML/JSON support for the REST-based called to the API.

The API accepts calls via a defined set of URL resources. For example, you can issue a query via the '/services/data/v20.0/query' resource. Simply set the ‘q’ parameter to the SOQL query text. Assuming you've already authenticated, making a REST call is as simple as performing an HTTP GET or POST. Here's some Java code for making a query:

HttpClient httpclient = new HttpClient();
GetMethod get = new GetMethod(instanceUrl
				+ "/services/data/v20.0/query");

// set the token in the header
get.setRequestHeader("Authorization", "OAuth " + accessToken);
// set the SOQL as a query param
NameValuePair[] params = new NameValuePair[1];

params[0] = new NameValuePair("q",
		"SELECT Name, Id from Account LIMIT 100");


This would result in a JSON array - something like the following:

  "done": true,
  "records": [
      "Id": "0015000000VALDtAAP",
      "Name": "GenePoint",
      "attributes": {
        "type": "Account",
        "url": "/services/data/v20.0/sobjects/Account/0015000000VALDtAAP"
      "Id": "0015000000VALDuAAP",
      "Name": "United Oil & Gas, UK",
      "attributes": {
        "type": "Account",
        "url": "/services/data/v20.0/sobjects/Account/0015000000VALDuAAP"

For more information, read Getting Started with the REST API.


The platform provides two WSDL files for API access:

  • Enterprise Web Services API (enterprise WSDL) — This API is for most enterprise users who are developing client applications for their organization. The enterprise WSDL file is a strongly typed representation of your organization’s data. It provides information about your schema, data types, and fields to your development environment, allowing for a tighter integration between it and the Web service. This WSDL changes if custom fields or custom objects are added to, renamed, or removed from your organization’s configuration.
  • Partner Web Services API (partner WSDL) — This API is for developers who are creating client applications for multiple organizations, or for developers who want to develop more flexible integrations. It is a loosely-typed representation of the object model within an organization, and so can be used to access data within any organization.

The most important difference between the two WSDLs is that the enterprise WSDL is strongly typed. In other words, if you create a persistent object MyList, then MyList will end up in the enterprise WSDL schema. It won’t end up in the partner WSDL schema though, which is loosely typed. You can still access the object, but you have to use more generic methods that are parameterized for each type.

These web services are also versioned. A new release of the platform may include new features in this API, and if that is so you can simply continue using the previous version of the web services WSDL.

You can accesses the WSDL files for your organization by navigating to Setup->Develop->API within the Builder environment. These WSDL files can then be used in your language of choice, and you can start interacting with the platform immediately. However, a number of language-specific toolkits are also provided that ease this process. After a simple example, we turn to look at these toolkits.

Every example that uses the WSDL will be written in some client language that consumes that WSDL. Here’s an example of some Java code that performs a login to the SOAP API, and which then proceeds with a query:

// First, log in
LoginResult loginResult=null; 
SoapBindingStub sfdc=null; 
sfdc = (SoapBindingStub) new SforceServiceLocator().getSoap(); 
// login 
loginResult = sfdc.login("username","password");   

// The set up some security related items
// Reset the SOAP endpoint to the returned server URL 
// Create a new session header object 
// add the session ID returned from the login 
SessionHeader sh=new SessionHeader(); 
sfdc.setHeader(new SforceServiceLocator().getServiceName().getNamespaceURI(), 

// now that we're logged in, make some calls - retrieve information about the user
GetUserInfoResult userInfo = sfdc.getUserInfo(); 

// create a new account object locally
Account account = new Account(); 
account.setName("My New Account");

SObject[] sObjects = new SObject[2]; 
sObjects[0] = account;

// persist the object
SaveResult[] saveResults = sfdc.create(sObjects);

The code should be reasonably self explanatory. The first section logs in using the generated SOAP stubs. The login call to the web service returns a server URL where subsequent web service calls must be made, and the second part of the code sets this and other security details. The final parts of the code make a call on the getUserInfo() web service to retrieve user information, and create for persisting data to the platform.

The above code uses the enterprise WSDL, which you may have guessed by the presence of the Account type. The enterprise WSDL schema reflects the types of the sObjects in the schema itself. In contrast, the partner WSDL is more flexible and loosely typed, and as a result creating a new record isn’t as simple. Here, for example, is some Java code to create an Account record:

MessageElement[] ac = new MessageElement[3]; 
ac[0] = new MessageElement(new QName("AccountNumber"),"002DF99ELK9"); 
ac[1] = new MessageElement(new QName("Name"),"My New Account"); 
ac[2] = new MessageElement(new QName("BillingCity"),"Glasgow"); 
SObject acO = new SObject(); 

We’ve omitted all the error-handling code you would typically find in an application, and of course the details will vary from language to language and on the client web services stack that you use—but this should give you a feel for what such an application will look like.

Chatter REST API

The Chatter REST API makes it easy to integrate mobile apps, intranet sites, and 3rd party web applications with Chatter. It provides resources for feeds, comments, likes, users, groups, private messages, and recommendations - using an optimized REST-based API.

Here, for example, is some Java code that updates the current status of a user by adding a new post to his Chatter feed:

OAuthTokens myTokens = globalState.getAccessTokens();
String url = myTokens.get_instance_url() + "/services/data/v23.0/chatter/feeds/news/me/feed-items?text=New+status+post";
HttpPost post = new HttpPost(url);
post.setHeader("Authorization", "OAuth " + myTokens.get_access_token());
post.setHeader("Content-type", "application/json");

DefaultHttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(post);

Notice how this is simply an HTTP POST, to the appropriate Chatter API URL for the resource, with OAuth authentication having already taken place.

For more details, see Getting Started with the Chatter REST API.


As the code example shows, the platform uses a variety of security mechanisms. A username and password are required to make an initial log in. The platform can be configured to allow logins only from particular domains, further strengthening this login—together with SSL and TLS support. Security tokens can be issued, which must be appended to passwords, to allow login from untrusted networks. SAML and other token mechanisms are also supported.

A Session ID is returned on a successful login, and this session ID must be included in all subsequent calls. Furthermore, the sharing metadata determining data access is also honored in all calls to the web services API, helping to ensure that users only get access to data that they’ve been permitted to see.

Data Replication

The SOAP API has two methods important to data replication integration.

The getDeleted() method retrieves the list of records that have been deleted within the given timespan for a specified object, while getUpdated() retrieves the list of records that have been updated (added or changed) during a specified timespan for the specified object.

These API calls return a set of IDs for records that have been updated (added or changed) or deleted, as well as the timestamp (Coordinated Universal Time (UTC)) indicating when they were last updated or deleted. You can then use these data to process these results and to incorporate the required changes into the local copy of the data.

Toolkits Built on the SOAP API

A number of data and cloud integration and language-specific toolkits exist that use the SOAP API. For example, the PHP Toolkit lets you seamlessly integrate with the platform from a PHP application - all you need is the web services end-point address. The toolkit does all the work of invoking the web services, and presents a useful PHP interface that you can program against. Similar toolkits are available for a variety of languages. This section provides a quick overview of each of these toolkits.


The PHP toolkit provides an easy way to make Web service API method calls from within PHP. The toolkit supports the Enterprise and Partner WSDL. Once you’ve installed the toolkit on your local PHP installation, you can write PHP code to interact with the Web services API. Here’s a simple PHP page that displays the result of a query.

require_once ('soapclient/SforcePartnerClient.php');

$mySforceConnection = new SforcePartnerClient();
$mySoapClient = $mySforceConnection->createConnection("partner.wsdl.xml");
$mylogin = $mySforceConnection->login("username", "password");
$query = "SELECT Id, FirstName, LastName from Contact";
$response = $mySforceConnection->query($query);
$queryResult = new QueryResult($response);
foreach ($queryResult->records as $record) {
  echo "Id = ".$sObject->Id;
  echo "First Name = ".$record->fields->FirstName;
  echo "Last Name = ".$record->fields->LastName;

AJAX Toolkit

The AJAX Toolkit is a JavaScript wrapper around the SOAP API. The toolkit is based on the loosely typed partner WSDL, and it supports a number of popular browsers. Using the AJAX Toolkit, you can write applications that run in the browser of the client, and which interact with the full SOAP API. These applications are called S-Controls.

Although this is a powerful extension to the SOAP API, you can often accomplish the same behavior far more optimally (faster, easier to code and more scalable) using the Visualforce technology, which lets you embed calls to the API within the user interface layer rendered on the server. With S-Controls, additional calls are made from the client to the server, and these round-trips will slow your applications down.

For more information on S-Controls and the AJAX Toolkit, see the formal documentation for the AJAX Toolkit.

Other Languages

There are a number of community-developed toolkits for many other languages. The Integration wiki page points to toolkits for:

  • Java
  • Perl
  • PHP
  • Ruby
  • Adobe Flex
  • .NET
  • Objective C and Cocoa

Data Tools

Two important tools that leverage the SOAP API are:

  • The Data Loader is a client application built around the SOAP API for the bulk import or export of data. Use it to insert, update, delete, or extract data.
  • The Excel Connector is an Excel plugin that lets you access and update your data directly from Microsoft Excel, allowing easy reporting, mass updating and cleansing of data.

Integrating the Cloud

The platform supports a number of toolkits that facilitate the integration between the platform and some other cloud platform. These toolkits are built around the fundamental integration points (such as HTTP/REST, and the SOAP API), and offer a useful level of abstraction:

Other Integration Options

The outbound messaging, email, web service and SOAP API provide powerful tools with which to build your own integrations. In addition, there are a number of other integration facilities available, some supplied by, and some by external vendors. Here’s an overview:

  • AppExchange provides a number of integration solutions for various middleware components.
  • provides a number of Desktop Connectors, for Microsoft Outlook, Lotus Notes and other products.
  • Salesforce to Salesforce allows two companies that are using the platform to share data with each other.


This article introduces the fundamental integration blocks available on the Platform. These include invoking external web services, hosting web services, HTTP and REST integration, email integration for inbound and outbound messaging, and the SOAP and REST APIs, which provides direct access to data and other functionality within an organization. The platform also has a number of toolkits built around the SOAP APIs, supporting a range of client platforms, including the Mobile SDK. Finally, AppExchange hosts a number of pre-built integration options, ranging from ERP connectors to integration solutions for middleware components.


About the Author

Jon Mountjoy is the community manager and editor-in-chief at Developer Force. He gets kicks out of learning new things and communicating these to the community. You can find Jon on the Developer Force blog, Twitter, FriendFeed and more. Jon says "Thank you to the awesome Platform Documentation team for their great documentation. Thanks also to Jesper Joergensen and Jesse Lorenz for their great suggestions and corrections. Please send me any feedback about the article!"