Before you can use the API, your user profile must have the "API Enabled" permission selected. This permission is enabled by default. For more information see the help in the Salesforce user interface. Use this topic to create a sample application in your development environment.
If you are not already a member of the developer community, go to http://www.salesforce.com/signup/dev_signup.jsp and follow the instructions for signing up for a Developer Edition account. Even if you already have an Enterprise Edition or Unlimited Edition account, it is strongly recommended that you use Developer Edition for developing, staging, and testing your solutions against sample data to protect your organization’s live data. This is especially true for applications that will be inserting, updating, or deleting data (as opposed to simply reading data).
To access the Force.com Web service, you need a Web Service Description Language (WSDL) file. The WSDL file defines the Web service that is available to you. Your development platform uses this WSDL to generate an API to access the Force.com Web service it defines. You can either obtain the WSDL file from your organization’s Salesforce administrator or you can generate it yourself if you have access to the WSDL download page in the Salesforce user interface. You can navigate to the most recent WSDL for your organization by clicking .
For more information about WSDL, see http://www.w3.org/TR/wsdl.
There are two Force.com Web services for which you can obtain WSDL files for API access:
Any user with the “Modify All Data” permission can download the Web Services Description Language (WSDL) file to integrate and extend Salesforce using the API. (The System Administrator profile has this permission.)
The WSDL file is dynamically generated based on which type of WSDL file (enterprise or partner) you download. The generated WSDL defines all of the API calls, objects (including standard and custom objects), and fields that are available for API access for your organization.
To generate the WSDL file for your organization:
Once you have the WSDL file, you need to import it into your development platform so that your development environment can generate the necessary objects for use in building client Web service applications in that environment. This section provides sample instructions for Apache Axis and Microsoft Visual Studio. For instructions about other development platforms, see your platform’s product documentation.
Java environments access the API through Java objects that serve as proxies for their server-side counterparts. Before using the API, you must first generate these objects from your organization’s WSDL file.
Each SOAP client has its own tool for this process. For Apache Axis, use the WSDL2Java utility.
The basic syntax for WSDL2Java is:
java –classpath pathToJAR/Filename org.apache.axis.wsdl.WSDL2Java -a pathToWsdl/WsdlFilename
The -a switch generates code for all elements, referenced or not, which may be necessary depending on your WSDL. For more information, see the WSDL2Java documentation.
If you have JAR files in more than one location, list them with a semicolon separating the files. For example, if the Axis JAR files are installed in C:\axis-1.3, and the WSDL is named my_enterprise.wsdl and is stored in C:\mywsdls:
java –classpath c:\axis-1.3\lib\axis.jar;c:\axis-1.3\lib\axis-ant.jar;c:\axis-1.3\lib\axis-schema.jar;c:\axis-1.3\lib\commons-discovery-0.2.jar;c:\axis-1.3\lib\commons-logging-1.0.4.jar;c:\axis-1.3\lib\jaxrpc.jar;c:\axis-1.3\lib\log4j-1.2.8.jar;c:\axis-1.3\lib\saaj.jar;c:\axis-1.3\lib\wsdl4j-1.5.2.jar;c:\axis-1.3\mail.jar;c:\axis-1.3\activation.jar;c:\axis-1.3\wsdl4j.jar; org.apache.axis.wsdl.WSDL2Java -a C:\mywsdls\my_enterprise.wsdl
This command will generate a set of folders and Java source code files in the same directory in which it was run. After these files are compiled, they can be included in your Java programs for use in creating client applications.
For most Java development environments, you can use wizard-based tools for this process instead of the command line. For more information about using WSDL2Java, see http://ws.apache.org/axis/java/reference.html. For more information about using WSDL2Java with Force.com, visit the message boards at http://www.salesforce.com/developer/boards.jsp.
Visual Studio languages access the API through objects that serve as proxies for their server-side counterparts. Before using the API, you must first generate these objects from your organization's WSDL file.
Visual Studio provides two approaches for importing your WSDL file and generating an XML Web service client: an IDE-based approach and a command line approach.
An XML Web service client is any component or application that references and uses an XML Web service. This does not necessarily need to be a client-based application. In fact, in many cases, your XML Web service clients might be other Web applications, such as Web Forms or even other XML Web services. When accessing XML Web services in managed code, a proxy class and the .NET Framework handle all of the infrastructure coding.
To access an XML Web service from managed code:
file:///c:\WSDLFiles\enterprise.wsdl
Unfortunately, in the definition of the SObject class, Visual Studio does not wrap these to class references in the System.Xml.Serialization.XmlIncludeAttribute that are part of the SObject definition. To work around this problem in Visual Studio, you need to edit the XmlIncludeAttribute settings for Case and Event as shown below. This does not apply to C# and only applies when using the enterprise version of the WSDL.
System.Xml.Serialization.XmlIncludeAttribute(GetType([Event])), _ System.Xml.Serialization.XmlIncludeAttribute(GetType([Case])), _
Once you have imported your WSDL file, you can begin building client applications that use the API. Use the following samples to create a basic client application. Comments embedded in the sample explain each section of code.
This section walks through a sample Java client application that uses the Apache Axis SOAP client. The purpose of this sample application is to show the required steps for logging into the login server and to demonstrate the invocation and subsequent handling of several API calls. This sample application performs the following main tasks:
All client applications that access the API must complete the tasks in this step before attempting any subsequent API calls.
Note the error handling code that follows each API call.
//The sample client application begins by importing the necessary packages and objects.
package com.doc.samples;
import java.io.*;
import java.rmi.RemoteException;
import javax.xml.rpc.ServiceException;
import com.sforce.soap.enterprise.*;
import com.sforce.soap.enterprise.fault.ExceptionCode;
import com.sforce.soap.enterprise.fault.LoginFault;
import com.sforce.soap.enterprise.sobject.Contact;
/**
* Title: Login Sample
*
* Description: Console application illustrating login, session management,
* and server redirection.
*
* Copyright: Copyright (c) 2005- 2008
* Company: salesforce.com
*
* @version 14.0
*/
public class Samples {
private SoapBindingStub binding;
static BufferedReader rdr = new BufferedReader(new InputStreamReader(System.in));
public Samples() {
}
public static void main(String[] args) throws ServiceException {
Samples samples1 = new Samples();
samples1.run();
}
//The sample client application retrieves the user's login credentials.
// Helper function for retrieving user input from the console
String getUserInput(String prompt) {
System.out.print(prompt);
try {
return rdr.readLine();
}
catch (IOException ex) {
return null;
}
}
/**
* The login call is used to obtain a token from Salesforce.
* This token must be passed to all other calls to provide
* authentication.
*/
private boolean login() throws ServiceException {
String userName = getUserInput("Enter username: ");
String password = getUserInput("Enter password: ");
/** Next, the sample client application initializes the binding stub.
* This is our main interface to the API through which all
* calls are made. The getSoap method takes an optional parameter,
* (a java.net.URL) which is the endpoint.
* For the login call, the parameter always starts with
* http(s)://www.salesforce.com. After logging in, the sample
* client application changes the endpoint to the one specified
* in the returned loginResult object.
*/
binding = (SoapBindingStub) new SforceServiceLocator().getSoap();
// Time out after a minute
binding.setTimeout(60000);
// Test operation
LoginResult loginResult;
try {
System.out.println("LOGGING IN NOW....");
loginResult = binding.login(userName, password);
}
catch (LoginFault ex) {
// The LoginFault derives from AxisFault
ExceptionCode exCode = ex.getExceptionCode();
if (exCode == ExceptionCode.FUNCTIONALITY_NOT_ENABLED ||
exCode == ExceptionCode.INVALID_CLIENT ||
exCode == ExceptionCode.INVALID_LOGIN ||
exCode == ExceptionCode.LOGIN_DURING_RESTRICTED_DOMAIN ||
exCode == ExceptionCode.LOGIN_DURING_RESTRICTED_TIME ||
exCode == ExceptionCode.ORG_LOCKED ||
exCode == ExceptionCode.PASSWORD_LOCKOUT ||
exCode == ExceptionCode.SERVER_UNAVAILABLE ||
exCode == ExceptionCode.TRIAL_EXPIRED ||
exCode == ExceptionCode.UNSUPPORTED_CLIENT) {
System.out.println("Please be sure that you have a valid username
and password.");
} else {
// Write the fault code to the console
System.out.println(ex.getExceptionCode());
// Write the fault message to the console
System.out.println("An unexpected error has occurred." + ex.getMessage());
}
return false;
} catch (Exception ex) {
System.out.println("An unexpected error has occurred: " + ex.getMessage());
ex.printStackTrace();
return false;
}
// Check if the password has expired
if (loginResult.isPasswordExpired()) {
System.out.println("An error has occurred. Your password has expired.");
return false;
}
/** Once the client application has logged in successfully, it will use
* the results of the login call to reset the endpoint of the service
* to the virtual server instance that is servicing your organization.
* To do this, the client application sets the ENDPOINT_ADDRESS_PROPERTY
* of the binding object using the URL returned from the LoginResult.
*/
binding._setProperty(SoapBindingStub.ENDPOINT_ADDRESS_PROPERTY,
loginResult.getServerUrl());
/** The sample client application now has an instance of the SoapBindingStub
* that is pointing to the correct endpoint. Next, the sample client application
* sets a persistent SOAP header (to be included on all subsequent calls that
* are made with the SoapBindingStub) that contains the valid sessionId
* for our login credentials. To do this, the sample client application
* creates a new SessionHeader object and set its sessionId property to the
* sessionId property from the LoginResult object.
*/
// Create a new session header object and add the session id
// from the login return object
SessionHeader sh = new SessionHeader();
sh.setSessionId(loginResult.getSessionId());
/** Next, the sample client application calls the setHeader method of the
* SoapBindingStub to add the header to all subsequent method calls. This
* header will persist until the SoapBindingStub is destroyed until the header
* is explicitly removed. The "SessionHeader" parameter is the name of the
* header to be added.
*/
// set the session header for subsequent call authentication
binding.setHeader(new SforceServiceLocator().getServiceName().getNamespaceURI(),
"SessionHeader", sh);
// return true to indicate that we are logged in, pointed
// at the right url and have our security token in place.
return true;
}
/**
* To determine the objects that are available to the logged-in user, the sample
* client application executes a describeGlobal call, which returns all of the
* objects that are visible to the logged-in user. This call should not be made
* more than once per session, as the data returned from the call likely does not
* change frequently. The DescribeGlobalResult is simply echoed to the console.
*/
private void describeGlobalSample() {
try {
DescribeGlobalResult describeGlobalResult;
describeGlobalResult = binding.describeGlobal();
String[] types = describeGlobalResult.getTypes();
for (String type : types) System.out.println(type);
getUserInput("\nDescribe global was successful.\n\nHit the enter key
to continue....");
}
catch (Exception ex) {
System.out.println("\nFailed to return types, error message was: \n"
+ ex.getMessage());
getUserInput("\nHit return to continue...");
}
}
/**
* The following code segment illustrates the type of metadata information that
* can be obtained for each object available to the user. The sample client
* application executes a describeSObject call on a given object and then echoes
* the returned metadata information to the console. Object metadata information
* includes permissions, field types and length and available values for picklist
* fields and types for referenceTo fields.
*/
private void describeSample() {
String objectToDescribe = getUserInput("\nType the name of the object to
describe (try Account): ");
try {
DescribeSObjectResult descSObjectRslt;
descSObjectRslt = binding.describeSObject(objectToDescribe);
if (descSObjectRslt != null) {
// Report object level information
Field[] fields = descSObjectRslt.getFields();
String objectName = descSObjectRslt.getName();
System.out.println("Metadata for " + objectToDescribe + " object:\n");
System.out.println("Object name = " + objectName);
System.out.println("Number of fields = " + fields.length);
System.out.println("Object can be activated = " +
descSObjectRslt.isActivateable());
System.out.println("Can create rows of data = " +
descSObjectRslt.isCreateable());
System.out.println("Object is custom object = " +
descSObjectRslt.isCustom());
System.out.println("Can delete rows of data = " +
descSObjectRslt.isDeletable());
System.out.println("Can query for rows of data = " +
descSObjectRslt.isQueryable());
System.out.println("Object used in replication = " +
descSObjectRslt.isReplicateable());
System.out.println("Can retrieve object = " +
descSObjectRslt.isRetrieveable());
System.out.println("Can search object = " +
descSObjectRslt.isSearchable());
System.out.println("Can un-delete = " +
descSObjectRslt.isUndeletable());
System.out.println("Can update = " +
descSObjectRslt.isUpdateable());
System.out.println("\nField metadata for " + objectToDescribe +
" object:\n");
// Report information about each field
if (fields != null) {
for (Field field : fields) {
PicklistEntry[] picklistValues = field.getPicklistValues();
String[] referenceTos = field.getReferenceTo();
System.out.println("************* New Field ***************");
System.out.println("Name = " + field.getName());
System.out.println("Label = " + field.getLabel());
System.out.println("Length = " + field.getLength());
System.out.println("Bytelength = " + field.getByteLength());
System.out.println("Digits = " + field.getDigits());
System.out.println("Precision = " + field.getPrecision());
System.out.println("Scale = " + field.getScale());
System.out.println("Field type = " + field.getType());
// field properties
System.out.println("Custom field = " + field.isCustom());
System.out.println("Name field = " + field.isNameField());
System.out.println("Can set field value on Create = " +
field.isCreateable());
System.out.println("Can set field value on Update = " +
field.isUpdateable());
System.out.println("Can be used to filter results = " +
field.isFilterable());
System.out.println("Field value can be empty = " +
field.isNillable());
System.out.println("Field value is defaulted on Create = " +
field.isDefaultedOnCreate());
System.out.println("Field value is calculated = " +
field.isCalculated());
System.out.println("Field value is a restricted picklist = " +
field.isRestrictedPicklist());
if (picklistValues != null) {
System.out.println("Picklist values = ");
for (PicklistEntry picklistValue : picklistValues) {
if (picklistValue.getLabel() != null)
System.out.print(" item: " + picklistValue.getLabel());
else
System.out.print(" item: " + picklistValue.getValue());
System.out.print(", value = " + picklistValue.getValue());
System.out.println(", is default = " +
picklistValue.isDefaultValue());
}
}
if (referenceTos != null) {
System.out.println("Field references the following objects:");
for (String referenceTo : referenceTos) System.out.println(" "
+ referenceTo);
}
System.out.println("");
}
getUserInput("\nDescribe " + objectToDescribe +
" was successful.\n\nHit the enter key to continue....");
}
}
} catch (Exception ex) {
System.out.println("\nFailed to get " + objectToDescribe +
" description, error message was: \n " + ex.getMessage());
getUserInput("\nHit return to continue...");
}
}
/**
* The sample client application executes a query by invoking the query call,
* passing a simple query string ("select FirstName, LastName from Contact")
* and iterating through the returned QueryResult.
*/
private void querySample() {
QueryOptions qo = new QueryOptions();
qo.setBatchSize(200);
binding.setHeader(new SforceServiceLocator().getServiceName().getNamespaceURI(),
"QueryOptions", qo);
try {
QueryResult qr = binding.query("select FirstName, LastName from Contact");
if (qr.getSize() > 0) {
System.out.println("Logged in user can see "
+ qr.getRecords().length + " contact records. ");
do {
// output contact records
for (int i = 0; i < qr.getRecords().length; i++) {
Contact con = (Contact) qr.getRecords(i);
String fName = con.getFirstName();
String lName = con.getLastName();
if (fName == null) {
System.out.println("Contact " + (i + 1) + ": "
+ lName);
} else {
System.out.println("Contact " + (i + 1) + ": "
+ fName + " " + lName);
}
}
if (!qr.isDone()) {
qr = binding.queryMore(qr.getQueryLocator());
} else {
break;
}
} while (qr.getSize() > 0);
} else {
System.out.println("No records found.");
}
getUserInput("Query succesfully executed. \nHit return to continue...");
} catch (ApiFault ex) {
System.out.println("\nFailed to execute query succesfully, error message was:
\n" + ex.getMessage());
getUserInput("\nHit return to continue...");
}
}
private void run() throws ServiceException {
if (login()) {
getUserInput("SUCESSFUL LOGIN! Hit the enter key to continue.");
describeGlobalSample();
describeSample();
querySample();
}
}
}
This section walks through a sample C# client application. The purpose of this sample application is to show the required steps for logging in and to demonstrate the invocation and subsequent handling of several API calls.
This sample application performs the following main tasks:
All client applications that access the API must complete the tasks in this step before attempting any subsequent API calls.
In the following sample code, API calls and other significant code is identified in a bold font. In addition, note the error handling code that follows each API call.
The following code begins the sample C# client application.
using System;
namespace Walkthrough
{
class WalkthroughSample
{
private sforce.SforceService binding;
static private WalkthroughSample walkthroughSample;
[STAThread]
static void Main(string[] args)
{
walkthroughSample = new WalkthroughSample();
walkthroughSample.run();
}
public void run()
{
//Call the login call
if ( login() )
{
//Do a describe global
describeGlobal();
//describe an account object
describeSObject("account");
//retrieve some data using query
querySample();
}
}
The login() method retrieves the user’s login credentials, instantiates a binding stub (which is the main interface to the API through which all calls are made), and invokes the login() call.
For the login() call, the initial endpoint is always http(s)//www.salesforce.com. Once the client application has logged in successfully, however, a client application uses the results of the login() call to reset the endpoint of the service to the virtual server instance that is servicing your organization. After logging in successfully, the sample client application:
private void login()
{
// Create service object
SforceService sfdc = new SforceService();
// Invoke the login call and save results in LoginResult
LoginResult lr = sfdc.login("username","password");
if (!lr.passwordExpired) {
// Reset the SOAP endpoint to the returned server URL
sfdc.Url = lr.serverUrl;
// Create a new session header object
// Add the session ID returned from the login
sfdc.SessionHeaderValue = new SessionHeader();
sfdc.SessionHeaderValue.sessionId = lr.sessionId;
GetUserInfoResult userInfo = lr.userInfo;
} else {
Console.Writeine("You password is expired.");
}
}
private void describeGlobal()
{
//The describe global will return an array of object names that
//are available to the logged-in user
sforce.DescribeGlobalResult dgr = binding.describeGlobal();Console.WriteLine("\nDescribe Global Results:\n");
//Loop through the array echoing the object names to the console
for (int i=0;i<dgr.types.Length;i++)
{
Console.WriteLine(dgr.types[i]);
}
Console.WriteLine("\n\nHit enter to continue...");
Console.ReadLine();
}
private void describeSObject(string objectType)
{
//Call the describeSObject passing in the object type name
sforce.DescribeSObjectResult dsr =
binding.describeSObject(objectType);
//The first properites we will echo are on the object itself
//First we will output some Descriptive info on the object
Console.WriteLine("\n\nObject Name: " + dsr.name);
if (dsr.custom) Console.WriteLine("Custom Object");
if (dsr.label != null) Console.WriteLine("Label: " + dsr.label);
//now the permissions on the object
if (dsr.activateable) Console.WriteLine("Activateable");
if (dsr.createable) Console.WriteLine("Createable");
if (dsr.deletable) Console.WriteLine("Deleteable");
if (dsr.queryable) Console.WriteLine("Queryable");
if (dsr.replicateable) Console.WriteLine("Replicateable");
if (dsr.retrieveable) Console.WriteLine("Retrieveable");
if (dsr.searchable) Console.WriteLine("Searchable");
if (dsr.undeletable) Console.WriteLine("Undeleteable");
if (dsr.updateable) Console.WriteLine("Updateable");
//Now we will retrieve meta-data about each of the fields
for (int i=0;i<dsr.fields.Length;i++)
{
//Create field object for readability
sforce.Field field = dsr.fields[i];
//Echo some useful information
Console.WriteLine("Field name: " + field.name);
Console.WriteLine("\tField Label: " + field.label);
//This next property indicates that this
//field is searched when using
//the name search group in SOSL
if (field.nameField)
Console.WriteLine("\tThis is a name field.");
if (field.restrictedPicklist)
Console.WriteLine("This is a RESTRICTED picklist field.");
Console.WriteLine("\tType is: " + field.type.ToString());
if (field.length > 0)
Console.WriteLine("\tLength: " + field.length);
if (field.scale > 0)
Console.WriteLine("\tScale: " + field.scale);
if (field.precision > 0)
Console.WriteLine("\tPrecision: " + field.precision);
if (field.digits > 0)
Console.WriteLine("\tDigits: " + field.digits);
if (field.custom)
Console.WriteLine("\tThis is a custom field.");
//Output the permission on this field.
if (field.nillable) Console.WriteLine("\tCan be nulled.");
if (field.createable) Console.WriteLine("\tCreateable");
if (field.filterable) Console.WriteLine("\tFilterable");
if (field.updateable) Console.WriteLine("\tUpdateable");
//If this is a picklist field, we will show the values
if (field.type.Equals(sforce.fieldType.picklist))
{
Console.WriteLine("\tPicklist Values");
for (int j=0;j<field.picklistValues.Length;j++)
Console.WriteLine("\t\t" + field.picklistValues[j].value);
}
//If this is a foreign key field (reference),
//we will show the values
if (field.type.Equals(sforce.fieldType.reference))
{
Console.WriteLine("\tCan reference these objects:");
for (int j=0;j<field.referenceTo.Length;j++)
Console.WriteLine("\t\t" + field.referenceTo[j]);
}
Console.WriteLine("");
}
Console.WriteLine("\n\nHit enter to continue...");
Console.ReadLine();
}
private void querySample()
{
//The results will be placed in qr
sforce.QueryResult qr = null;
//We are going to increase our return batch size to 250 items
//Setting is a recommendation only, different batch sizes may
//be returned depending on data, to keep performance optimized.
binding.QueryOptionsValue = new sforce.QueryOptions();
binding.QueryOptionsValue.batchSize = 250;
binding.QueryOptionsValue.batchSizeSpecified = true;
try
{
qr = binding.query("select FirstName, LastName from Contact");
bool done = false;
if (qr.size > 0)
{
Console.WriteLine("Logged-in user can see "
+ qr.records.Length + " contact records.");
while (!done)
{
Console.WriteLine("");
for (int i=0;i<qr.records.Length;i++)
{
sforce.Contact con = (sforce.Contact)qr.records[i];
string fName = con.FirstName;
string lName = con.LastName;
if (fName == null)
Console.WriteLine("Contact " + (i + 1) + ": " + lName);
else
Console.WriteLine("Contact " + (i + 1) + ": " + fName
+ " " + lName);
}
if (qr.done)
{
done = true;
}
else
{
qr = binding.queryMore(qr.queryLocator);
}
}
}
else
{
Console.WriteLine("No records found.");
}
}
catch (Exception ex)
{
Console.WriteLine("\nFailed to execute query succesfully,
error message was: \n" + ex.Message);
}
Console.WriteLine("\n\nHit enter to exit...");
Console.ReadLine();
}
}
}