Integrating with the Force.com Platform
Integrating with the Force.com Platform
Abstract
The Force.com Platform 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 supplies the Force.com Web Services API, providing the basis for integration with other languages such as Java, .NET and PHP, and the AJAX Toolkit, providing the basis for in-browser mashups.
This article provides an overview of the fundamental developer integration points available on the Force.com 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 Force.com 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 Force.com Web Services API. This is a SOAP based web service API that provides direct access to data within your organization. Using this, you can create a client that integrates with the platform from your language of choice. Toolkits that wrap around this API provide utility classes that make this integration even easier for a range of languages, including Java, .NET, PHP 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 Force.com 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 Force.com Web Services API and associated toolkits, such as the AJAX Toolkit, Java, .NET, PHP and Adobe Flex integrations.
- Syndication feeds via Force.com 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 Force.com platform from some external system.
Apex is a strongly-typed programming language that executes on the Force.com 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 Force.com 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;
return c.id;
}
}
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 Force.com 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 Force.com 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 Force.com 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.
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;
request_x.phone = phone;
Map<String, myWS.LookupPhoneResponse_element> response_map_x =
new Map<String, myWS.LookupPhoneResponse_element>();
response_map_x.put('response_x', response_x);
WebServiceCallout.invoke(
this,
request_x,
response_map_x,
new String[]{endpoint_x,
'http://www.mydomain.com/LookupPhone',
'http://www.mydomain.com','LookupPhone',
'http://www.mydomain.com','LookupPhoneResponse',
'myWS.LookupPhoneResponse_element'}
);
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 Force.com 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 Force.com platform using the Force.com Web Services 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 salesforce.com servers, and the payload includes your organization ID, which you can verify.
The following figure summarizes the actions of the outbound messaging service.
Setting up outbound messaging is a three step process:
- Set up the workflow rules and approval processes.
- Set up the outbound message workflow action that will fire when the workflow rules fire..
- Download the generated WSDL
- 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 Force.com.
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:
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 Force.com Web Services API Developer's Guide.
Inbound and Outbound: HTTP and REST
The Apex language also provides a way to make HTTP calls. There are three classes primarily used to make these types of requests:
- The
Httpclass is used to initiate HTTP requests and responses. - The
HttpRequestclass is used to create GET, PUT, POST and DELETE requests, manipulate request headers, configure timeouts and more. - The
HttpResponseclass 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();
req.setEndpoint(url);
req.setMethod('GET');
//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 Force.com 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 Force.com platform provides a way to access inbound and outbound email functionality for integration. Force.com 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[]{'user@acme.com'};
mail.setToAddresses(toAddresses);
mail.setReplyTo('support@acme.com');
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 the Apex Language Reference for documentation on the Email classes.
Outbound: Force.com Sites Syndication Feeds
Force.com Sites, a technology still in Developer Preview, enables you to create public websites and applications that run natively on the Force.com 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.
Inbound: Force.com Web Services API
The Force.com Web Services API is a SOAP web services API that provides you with direct access to your Force.com 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 Force.com Web Services API is the most fundamental integration point. It provides direct access to data within your application (organization), allowing you to query, create, delete and modify these data. It also provides 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 API to perform utility calls, such as changing a user’s password, retrieving the server’s time stamp or sending an email.
The platform provides two WSDL files for API access:
- Force.com 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 Force.com Web service. This WSDL changes if custom fields or custom objects are added to, renamed, or removed from your organization’s configuration.
- Force.com 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 Force.com 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.
A Simple Example
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 Force.com Web services 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
sfdc._setProperty(SoapBindingStub.ENDPOINT_ADDRESS_PROPERTY,loginResult.getServerUrl());
// Create a new session header object
// add the session ID returned from the login
SessionHeader sh=new SessionHeader();
sh.setSessionId(loginResult.getSessionId());
sfdc.setHeader(new SforceServiceLocator().getServiceName().getNamespaceURI(),
"SessionHeader",sh);
// 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.setAccountNumber("002DF99ELK9");
account.setName("My New Account");
account.setBillingCity("Glasgow")
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();
acO.setType("Account");
acO.set_any(ac);
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.
Security
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 Force.com Web Services 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 Force.com Web Services API
A number of data and cloud integration and language-specific toolkits exist that use the Force.com Web Services 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.
PHP
The PHP toolkit provides an easy way to make Force.com 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 Force.com Web services 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 web services API. These applications are called S-Controls.
Although this is a powerful extension to the web services 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 Web Services API 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 Web Services API are:
- The Data Loader is a client application built around the Force.com Web Services API for the bulk import or export of data. Use it to insert, update, delete, or extract data.
- The Force.com 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 Force.com platform supports a number of native toolkits that facilitate the integration between the Force.com platform and some other cloud platform. These toolkits are built around the fundamental integration points (such as HTTP/REST, and the Force.com Web Services API), and offer a useful level of abstraction:
- Force.com Toolkit for Google Data APIs exposes the Google Data APIs directly within Apex, making it easier to access them natively from your Force.com applications.
- Force.com for Google App Engine is a Python library and test harness that lets you access the Force.com Web services API from within Google App Engine applications.
- Force.com for Amazon Web Services exposes the Amazon Web Services Simple Storage System (S3) services natively in the Force.com environment, providing a set of wrappers around the S3 API and access methods, making them directly available to your own Apex application code.
- Force.com for Facebook gives you direct access to the Facebook APIs from within Apex Code.
Other Integration Options
The outbound messaging, email, web service and Force.com Web Services 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 salesforce.com, and some by external vendors. Here’s an overview:
- ERP Connectors – Salesforce.com and ISVs provide a number of ERP connectors (for Oracle, SAP and more) that offer bi-directional synchronization between platform data and ERP data. See the connector page for more information.
- Force.com AppExchange provides a number of integration solutions for various middleware components.
- Salesforce.com provides a number of Desktop Connectors, for Microsoft Outlook, Lotus Notes and other products.
- Salesforce to Salesforce allows two companies that are using the Force.com Platform to share data with each other.
Summary
This article introduces the fundamental integration blocks available on the Force.com Platform. These include invoking external web services, hosting web services, HTTP and REST integration, email integration for inbound and outbound messaging, and the Force.com Web Services API, which provides direct access to data and other functionality within an organization. The platform also has a number of toolkits built around the Web Services API, supporting a range of client platforms. Finally, Force.com AppExchange hosts a number of pre-built integration options, ranging from ERP connectors to integration solutions for middleware components.
References
- Developer Force provides access to free developer edition accounts, which you can use to start programming in Apex immediately. It also provides links to documentation, forums, and more.
- An Introduction to the Force.com Database provides a much more comprehensive introduction to the Force.com Database.
- An Introduction to Force.com Apex Code provides a comprehensive introduction to the Apex language, providing a lot more detail on all topics covered in this document.
- The Apex Language Reference provides a comprehensive introduction to the Apex language, providing a lot more detail on all topics covered in this document.
- The Force.com Web Services API Developer's Guide product documentation provides the ultimate reference for the Force.com Web Services API.
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!"

