2024年1月31日发(作者:)
Web Services API快速入门教程
什么时候应该使用Web Services API?
这个预建应用程序提供了强大的CRM功能。此外,提供能够自定义预置的应用程序,以适应您的组织。但是,您的组织可能有复杂的业务流程,是由现有的功能支持。当这种情况下,在平台为开发人员提供了实现自定义的方式去实现自己的业务需要。这些包括了Web services API,,apex,Visualforce服务。
Web Services API
使用Web Services API 创建,检索,更新或删除等帐目记录,自定义对象。API还允许您维护密码,执行搜索,等等。使用任何语言都可以支持Web Services API。
Metadata API
使用Metadata API来检索,部署,创建,更新或删除自定义信息,如自定义对象定义和页面布局为您的组织,。最常见的用法是从沙盒迁移或测试组织到生产组织的变化。Metadata
API是用于管理和建立自定义工具,可以管理Metadata data模型,而不是数据本身。要创建,检索,更新或删除,例如帐户或线索记录,使用API来管理您的数据。
最简单的方式来访问Metadata API中的功能是用在 IDE或迁移工具。这些工具是建立在Metadata API之上,并使用标准的Eclipse和Ant工具,分别以简化与元数据API的工作任务。在Eclipse平台为基础,在 IDE提供了一个集成开发环境与程序员熟悉舒适的环境,让您的代码,编译,测试和部署在IDE本身所有。
Apex
使用Apex如果你希望:
创建Web服务
创建电子邮件服务
执行复杂的验证多个对象
创建复杂的业务流程所不支持的过程
创建定制的事务逻辑(逻辑发生在整个交易,只需用一个单个记录或对象不)
将自定义逻辑来一次手术,如保存记录,以便它在操作时发生执行,无论它在用户界面,Visualforce页,或从Web服务API起源
Visualforce
Visualforce包括一个基于标记的标记语言,让开发人员构建应用程序和定制这个用户界面更强大的方法。随着Visualforce您可以:
建立多步向导和其它程序
通过应用程序创建自己的自定义流程控制
定义最佳,高效应用的交互导航模式和数据的具体规则
支持的版本
使用API,您的组织必须使用企业版,开发版。如果您是现有的的客户,
并希望升级到企业或无限制版,请联系您的客户代表。
开发Web服务客户端应用程序,强烈建议您使用开发人员测试,这是你的翻版的部署,包括所有的定制和数据。
符合标准
Simple Object Access Protocol (SOAP) 1.1
/TR/2000/NOTE-SOAP-20000508
Web Service Description Language (WSDL) 1.1
/TR/2001/NOTE-wsdl-20010315
WS-I Basic Profile 1.1
/Profiles/
开发平台
Visual Studio。NET 2005中,和Apache Axis 1.3和JDK 5.0(Java 2平台标准版开发套件5.0)。
快速启动
第1步:获取公司开发版帐户
如果您还不是开发社区的成员,去/join并按照签订的开发版帐户的指示。即使你已经拥有的是企业版或无限版帐户,则强烈建议您用于开发,分期,对样本数据和测试您的解决方案,以保护您的组织的实时数据,开发人员版。这是真正的应用,尤其是将要插入,更新或删除数据(而不是简单的读数据)。
如果您已经有一个开发版的帐户,确认您的用户配置文件的―API启用‖权限选中。此权限是默认启用。欲了解更多信息,请参阅在这个用户界面的帮助。
2步:生成或获取 WSDL
要访问的 Web服务,你需要一个Web服务描述语言(WSDL)文件。 WSDL文件定义的Web服务是提供给您。您的开发平台使用此WSDL生成的API来访问它的 Web服务定义。您可以从您的组织获得的管理员WSDL文件
也可以通过点击设置、开发,API
为您的组织生成WSDL文件
任何具有―修改所有数据‖权限可以下载Web服务描述语言(WSDL)文件,整合和扩展使用API的用户。 (系统管理员有此权限配置文件。)
WSDL文件是动态生成此基础上,对WSDL文件(企业或合伙人)类型下载。生成的WSDL定义了所有的API调用,对象(包括标准和自定义对象),字段可用于您的组织的API访问。
要生成您的组织的WSDL文件:
1 您必须登录以管理员或用户谁拥有―修改所有数据‖的权限。登录进行检查,以确保他们
从一个已知的IP地址
2
按一下您的姓名|设置|人才培养| API显示下载网页的WSDL
如果您正在下载WSDL和你的企业在组织管理,按企业的WSDL生成安装包。
将提示您选择安装的软件包的每个要包括在生成的WSDL版本。
否则,右键单击适当的WSDL文件,将它保存到本地目录的链接。在右键菜单,IE浏览器用户可以选择目标另存为
3 导入的WSDL文件到您的开发平台
Instructions for Java Environments (Apache Axis)
WSDL2Java的基本语法是:
java –classpath pathToJAR/Filename 2Java -a
pathToWsdl/WsdlFilename
java–classpath
c:;c:;c:;
c:;c:;
c:;c:;c:;
c:;c:;c:;
c:; 2Java -a
C:mywsdlsmy_
4示例代码
Java代码
1. 用户名和密码
2. 调用login(),如果login成功
a) 设置返回到会话的SessionID header
b) 复位到返回的serverUrl,这是后续API调用目标端点
3. 调用describeGlobal()来检索所有可用对象为该组织的数据列表。
4. 调用describeSObject()来检索指定对象的元数据(字段列表和对象属性)。
5.调用查询(),传递一个简单的查询字符串(―选择名字,从联系姓氏‖),并遍历返回QueryResult
//The sample client application begins by importing the necessary packages and objects.
package s;
import .*;
import Exception;
import eException;
import rise.*;
import ionCode;
import ault;
import t;
/**
* Title: Login Sample
*
* Description: Console application illustrating login, session management,
* and server redirection.
*
* Copyright: Copyright (c) 2005- 2008
* Company:
*
* @version 14.0
*/
public class Samples {
private SoapBindingStub binding;
static BufferedReader rdr = new BufferedReader(new
InputStreamReader());
public Samples() {
}
public static void main(String[] args) throws ServiceException {
Samples samples1 = new Samples();
();
}
//The sample client application retrieves the user's login credentials.
// Helper function for retrieving user input from the console
String getUserInput(String prompt) {
(prompt);
try {
return ne();
}
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 ) which is the endpoint.
* For the login call, the parameter always starts with
* http(s)://. 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
eout(60000);
// Test operation
LoginResult loginResult;
try {
n("LOGGING ");
loginResult = (userName, password);
}
catch (LoginFault ex) {
// The LoginFault derives from AxisFault
ExceptionCode exCode = eptionCode();
if (exCode == ONALITY_NOT_ENABLED ||
exCode == D_CLIENT ||
exCode == D_LOGIN ||
exCode == _DURING_RESTRICTED_DOMAIN
||
exCode == _DURING_RESTRICTED_TIME ||
exCode == _LOCKED ||
exCode == RD_LOCKOUT ||
exCode == _UNAVAILABLE ||
exCode == _EXPIRED ||
exCode == ORTED_CLIENT) {
n("Please be sure that you have a valid username " +
"and password.");
} else {
// Write the fault code to the console
n(eptionCode());
// Write the fault message to the console
n("An unexpected error has occurred." +
sage());
}
return false;
} catch (Exception ex) {
n("An unexpected error has occurred: " +
sage());
tackTrace();
return false;
}
// Check if the password has expired
if (wordExpired()) {
n("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(NT_ADDRESS_PROPERTY,
verUrl());
/** 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();
sionId(sionId());
/** 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
der(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 = null;
describeGlobalResult = beGlobal();
DescribeGlobalSObjectResult[] sobjectResults
= jects();
for (int i=0;i<;i++) {
n(sobjectResults[i].getName());
}
}
catch (Exception ex)
{
n("nFailed to return types, error message was: n" +
sage());
}
}
/**
* 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 = beSObject(objectToDescribe);
if (descSObjectRslt != null) {
// Report object level information
Field[] fields = lds();
String objectName = e();
n("Metadata for " + objectToDescribe + " object:n");
n("Object name = " + objectName);
n("Number of fields = " + );
n("Object can be activated = " +
vateable());
n("Can create rows of data = " +
teable());
n("Object is custom object = " +
om());
n("Can delete rows of data = " +
table());
n("Can query for rows of data = " +
yable());
n("Object used in replication = " +
icateable());
n("Can retrieve object = " +
ieveable());
n("Can search object = " +
chable());
n("Can un-delete = " +
letable());
n("Can update = " +
teable());
n("nField metadata for " + objectToDescribe +
" object:n");
// Report information about each field
if (fields != null) {
for (Field field : fields) {
PicklistEntry[] picklistValues = klistValues();
String[] referenceTos = erenceTo();
n("************* New Field ***************");
n("Name = " + e());
n("Label = " + el());
n("Length = " + gth());
n("Bytelength = " + eLength());
n("Digits = " + its());
n("Precision = " + cision());
n("Scale = " + le());
n("Field type = " + e());
// field properties
n("Custom field = " + om());
n("Name field = " + Field());
n("Can set field value on Create = " +
teable());
n("Can set field value on Update = " +
teable());
n("Can be used to filter results = " +
erable());
n("Field value can be empty = " +
able());
n("Field value is defaulted on Create = " +
ultedOnCreate());
n("Field value is calculated = " +
ulated());
n("Field value is a restricted picklist = " +
rictedPicklist());
if (picklistValues != null) {
n("Picklist values = ");
for (PicklistEntry picklistValue : picklistValues) {
if (el() != null)
(" item: " +
el());
else
(" item: " +
ue());
(", value = " +
ue());
n(", is default = " +
ultValue());
}
}
if (referenceTos != null) {
n("Field references the following
objects:");
for (String referenceTo : referenceTos)
n(" "
+ referenceTo);
}
n("");
}
getUserInput("nDescribe " + objectToDescribe +
" was the enter key ");
}
}
} catch (Exception ex) {
n("nFailed to get " + objectToDescribe +
" description, error message was: n " + sage());
getUserInput("nHit return ");
}
}
/**
* 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();
chSize(200);
der(new
SforceServiceLocator().getServiceName().getNamespaceURI(),
"QueryOptions", qo);
try {
QueryResult qr = ("select FirstName, LastName from
Contact");
if (e() > 0) {
n("Logged in user can see "
+ ords().length + " contact records. ");
do {
// output contact records
for (int i = 0; i < ords().length; i++) {
Contact con = (Contact) ords(i);
String fName = stName();
String lName = tName();
if (fName == null) {
n("Contact " + (i + 1) + ": "
+ lName);
} else {
n("Contact " + (i + 1) + ": "
+ fName + " " + lName);
}
}
if (!()) {
qr = ore(ryLocator());
} else {
break;
}
} while (e() > 0);
} else {
n("No records found.");
}
getUserInput("Query succesfully executed. nHit return ");
} catch (RemoteException ex) {
n("nFailed to execute query succesfully, error message was:"
+
"n" + sage());
getUserInput("nHit return ");
}
}
private void run() throws ServiceException {
if (login()) {
getUserInput("SUCCESSFUL LOGIN! Hit the enter key to continue.");
describeGlobalSample();
describeSample();
querySample();
}
}
}
C# Sample Code
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:
1.
2.
Prompts the user for their username and password.
Calls login() to log in to the single login server and, if the login succeeds:
o
o
Sets the returned
sessionId into the session header, which is required for session
authentication on subsequent API calls.
Resets the endpoint to the returned
serverUrl, which is the target of
subsequent API calls.
All client applications that access the API must complete the tasks in this step before
attempting any subsequent API calls.
3. Calls describeGlobal() to retrieve a list of all available objects for the organization’s data. The
describeGlobal method determines the objects that are available to the logged in user. This call
should not be made more than once per session, since the data returned from the call is not likely
to change frequently. The DescribeGlobalResult is echoed to the console.
4. Calls describeSObject() to retrieve metadata (field list and object properties) for a specified
object. The describeSObject method 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 lengths, and
available values for picklist fields and types for referenceTo fields.
5. Calls query(), passing a simple query string ("SELECT FirstName, LastName FROM Contact"),
and iterating through the returned QueryResult.
In the following sample code, API calls and other significant code are 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;
using c;
using ;
using ols;
using ;
namespace Walkthrough
{
class WalkthroughSample
{
private SforceService binding;
static private WalkthroughSample walkthroughSample;
[STAThread]
static void Main(string[] args)
{
walkthroughSample = new WalkthroughSample();
();
}
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();
}
}
private bool login()
{
("Enter username: ");
string username = ne();
("Enter password: ");
string password = ne();
// Create a service object
binding = new SforceService();
// Timeout after a minute
t = 60000;
// Try logging in
LoginResult lr;
try
{
ine("LOGGING ");
lr = (username, password);
}
// ApiFault is a proxy stub generated from the WSDL contract when
// the web service was imported
catch (SoapException e)
{
// Write the fault code to the console
ine();
// Write the fault message to the console
ine("An unexpected error has occurred: " + e);
// Write the stack trace to the console
ine(race);
// Return False to indicate that the login was not successful
return false;
}
// Check if the password has expired
if (rdExpired)
{
ine("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
*/
= Url;
/** The sample client application now has an instance of the SforceService
* 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 SforceService) that contains the
* valid sessionId for our login credentials. To do this, the sample
* client application creates a new SessionHeader object and persist it to
* the SforceService. Add the session ID returned from the login to the
* session header
*/
nHeaderValue = new SessionHeader();
nId = nId;
// Return true to indicate that we are logged in, pointed
// at the right URL and have our security token in place.
return true;
}
private void describeGlobal()
{
//describeGlobal returns an array of object results that
//includes the object names that are available to the logged-in user
DescribeGlobalResult dgr = beGlobal();
ine("nDescribe Global Results:n");
//Loop through the array echoing the object names to the console
for (int i = 0; i < ; i++)
{
ine(ts[i].name);
}
ine("nnHit enter ");
ne();
}
private void describeSObject(string objectType)
{
//Call the describeSObject passing in the object type name
DescribeSObjectResult dsr =
beSObject(objectType);
//The first properites we will echo are on the object itself
//First we will output some Descriptive info on the object
ine("nnObject Name: " + );
if () ine("Custom Object");
if ( != null) ine("Label: " + );
//now the permissions on the object
if (teable) ine("Activateable");
if (able) ine("Createable");
if (ble) ine("Deleteable");
if (ble) ine("Queryable");
if (ateable) ine("Replicateable");
if (veable) ine("Retrieveable");
if (able) ine("Searchable");
if (table) ine("Undeleteable");
if (able) ine("Updateable");
//Now we will retrieve meta-data about each of the fields
for (int i = 0; i < ; i++)
{
//Create field object for readability
Field field = [i];
//Echo some useful information
ine("Field name: " + );
ine("tField Label: " + );
//This next property indicates that this
//field is searched when using
//the name search group in SOSL
if (eld)
ine("tThis is a name field.");
if (ctedPicklist)
ine("This is a RESTRICTED picklist field.");
ine("tType is: " + ng());
if ( > 0)
ine("tLength: " + );
if ( > 0)
ine("tScale: " + );
if (ion > 0)
ine("tPrecision: " + ion);
if ( > 0)
ine("tDigits: " + );
if ()
ine("tThis is a custom field.");
//Output the permission on this field.
if (le) ine("tCan be nulled.");
if (able) ine("tCreateable");
if (able) ine("tFilterable");
if (able) ine("tUpdateable");
//If this is a picklist field, we will show the values
if ((st))
{
ine("tPicklist Values");
for (int j = 0; j < ; j++)
ine("tt" + stValues[j].value);
}
//If this is a foreign key field (reference),
//we will show the values
if ((nce))
{
ine("tCan reference these objects:");
for (int j = 0; j < ; j++)
ine("tt" + nceTo[j]);
}
ine("");
}
ine("nnHit enter ");
ne();
}
private void querySample()
{
//The results will be placed in qr
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.
ptionsValue = new QueryOptions();
ize = 250;
izeSpecified = true;
try
{
qr = ("select FirstName, LastName from Contact");
bool done = false;
if ( > 0)
{
ine("Logged-in user can see "
+ + " contact records.");
while (!done)
{
ine("");
for (int i = 0; i < ; i++)
{
Contact con = (Contact)s[i];
string fName = ame;
string lName = me;
if (fName == null)
ine("Contact " + (i + 1) + ": " + lName);
else
ine("Contact " + (i + 1) + ": " + fName
+ " " + lName);
}
if ()
{
done = true;
}
else
{
qr = ore(ocator);
}
}
}
else
{
ine("No records found.");
}
}
catch (Exception ex)
{
ine("nFailed to execute query succesfully," +
"error message was: n{0}", e);
}
ine("nnHit enter ");
ne();
}
}
}
基础 API的调用
自动提交对误差回滚
默认情况下,每一个操作,写入公司的对象是自动提交。这类似于在SQL
AUTOCOMMMIT设置。在创建(),更新()和delete()的调用尝试写入一个对象的多个记录,每个记录的写操作是作为一个单独的事务处理。例如,如果客户端应用程序试图创建两个新的帐户,他们创建的不是互相排斥的一组插入操作成功或失败个别
除非所有记录都成功处理
对于API版本20.0和更高版本AllOrNoneHeader允许调用回滚所有的改变,这个头是支持的Create(),delete(),undelete(),update()方法,和upsert()调用。
影响API调用的因素
您的组织必须启用API访问,并且用户试图访问API必须有个人资料的权限的“API启用”选中。这是默认选中。
根据您使用的是其中的WSDL
Enterprise WSDL: The generated enterprise WSDL file contains all of the objects that are
available to your organization. Via the API, a client application can access objects that are
defined in your enterprise WSDL file.
Partner WSDL: When using the generated partner WSDL file, a client application can access
objects that are returned in the describeGlobal() call.
Some objects may not appear in the WSDL because you must first contact and
request access, for example Territory orCampaign. These objects are noted in the ―Usage‖
section for each object.
Whether your configured permissions allow access to the data. Your client application logs in
as a user to the Web Service. The profile associated with the logged-in user grants
or denies access to specific objects and fields in your organization.
For certain objects, the user profile is configured with one of the following permissions:
Read—Users can only view objects of this type.
Create—Users can read and create objects of this type.
Edit—Users can read and update objects of this type.
Delete—Users can read, edit, and delete objects of this type


发布评论