1. Webservices In Salesforce (Part 1)
Presenter: Surya Kanta Mekap,
Mindfire Solutions
Email: suryam@mindfiresolutions.com
SkypeId: mfsi_suryam
Date: 4 Oct 2013
2. Overview
1. Introduction
2. What is SOAP?
3. What is REST?
4. SOAP vs REST
5. What to Choose?
6. SOAP Webservice
7. Public SOAP Webservice
8. SOAP Callout
9. Testing Webservice Callout
10. Summary
3. Webservice?
Webservice is a sofware function or method of an application exposed
to the outside world allowing other application to invoke it from the
web.
4. What is SOAP?
The Simple Object Access Protocol(SOAP) web service is a
architecture pattern, which specifies the basic rules to be considered
while designing web service platforms. The SOAP message itself
consists of an envelope, inside of which are the SOAP headers and
body, the actual information we want to send. It is based on the
standard XML format, designed especially to transport and store
structured data. SOAP may also refer to the format of the XML that the
envelope uses.
Best for activity oriented services. An activity is more than just
insert or update or delete a record.
5. What is REST?
Representational State Transfer(REST) is another architectural
pattern. Unlike SOAP, RESTful applications use the GET, POST, PUT
and DELETE to perform CRUD operations. REST is resource-oriented
and uses URI (or RESTful URLs).
Roy Fielding is the Man who introduced the word REST and the
concept in his doctoral thesis in 2000.
It’s an excellent choice of technology for use with mobile
applications and browser-based clients.
6. SOAP vs REST
●
●
●
●
●
●
●
●
SOAP is a XML based messaging protocol and REST is not a protocol but an
architectural style.
SOAP has a standard specification but there is none for REST.
Even SOAP based web services can be implemented in RESTful style. REST is a concept
that does not tie with any protocols.
REST does not enforces message format as XML or JSON or etc. But SOAP is XML
based message protocol.
REST follows stateless model. SOAP has specifications for stateful implementation as
well.
SOAP is strongly typed, has strict specification for every part of implementation. But
REST gives the concept and less restrictive about the implementation.
SOAP uses interfaces(WSDL) and named operations to expose business logic. REST uses
(generally) URI and methods like (GET, PUT, POST, DELETE) to expose resources.
REST only works over HTTP and HTTPS. SOAP works over HTTP, HTTPS, SMTP,
XMPP, etc.
7. What to Choose?
If you want a web service that is activity oriented or requires
additional level of security or secure messaging then SOAP service is
the best option to choose. Activity is much more than just CRUD
operations.
If you want a web service that is more of resource-oriented, need to
do some CRUD operation on a resource then REST service is the best
option to choose. Due to its light weight it is mostly preferred for
browser based and mobile based applications.
In general, when you're publishing an API to the outside world that
is either complex or likely to change, SOAP will be more useful. Other
than that, REST is usually the better option.
8. SOAP Webservice
1. First, create and define an Apex class as global. Then create and define an
Apex method using both the static and webservice modifiers as shown
below.
global class HelloWorld {
webService static string sayHello(){
return 'Hello';
}
}
The global access modifier declares that the class is visible to all Apex
scripts everywhere.
This means the class can be used by any Apex code, not just the Apex in the
same application.
9. SOAP Webservice(Continued...)
2. To access the webservice WSDL, go to Setup | App Setup | Develop | Apex
Classes, find the specific class where the web service is defined and click on
the WSDL hyperlink and download it.
3. Collect the Enterprise WSDL from Setup | App Setup | Develop | API by
clicking Generate Enterprise WSDL link.
The Partner and Enterprise WSDL have a login() method for which we
need it along with our custom webservice wsdl so that we can give the
username and password, get the session id, and then switch over to our
custom web service to make it work. Session ids are tied to a given user in the
organization, so we need to control what they can access by giving them their
own profile and locking down access to only what they need to get to.
Those are the WSDL files which are to be imported into the external
application(s) that will be invoking the web service.
10. SOAP Webservice(Continued...)
●
●
●
●
●
●
●
The webservice modifier can't be used on a class itself, or an interface or
interface methods or variables.
The @future annotation needs to be used to make the Apex method
execute asynchronously.
Asynchronous callouts can be made with triggers but synchronous callout
with trigger is not supported(use actionpoller to check and show if a
response has been received while other transactions were ongoing).
All classes or inner classes that contain methods or variables defined with
the webservice keyword must be declared as global.
You must define any method that uses the webservice keyword as static.
Methods defined with the webservice keyword cannot take the following
elements as parameters. While these elements can be used within the
method, they cannot be used as return values.
Maps, Sets, Pattern objects, Matcher objects, Exception objects.
You must use the webservice keyword with any member variables that
you want to expose as part of a web service.
11. Public SOAP Webservice
1) Create a SOAP webservice.
2) Go to Site > Setup > App Setup > Develop > Sites > Select your Site >
Give access of class "MerchandiseManager" to site profile
3) Extract WSDL of your class, go to your class and then click "Generate
WSDL". Now all we need to change the SOAP address location in the
generated WSDL soap:address tag location value.
Lets say this is the location:
https://ap1.salesforce.com/services/Soap/class/HelloWorld
And our site URL is
https://mindfire-surya-developer-edition.ap1.force.com/
So our final location will be:
https://mindfire-surya-developeredition.ap1.force.com/services/Soap/class/HelloWorld
12. SOAP Callout
Apex Callouts enable Apex to invoke external SOAP web services using
WSDL so that you connect to third party services.
Before any Apex callout can call an external site, that site must be
registered in the Remote Site Settings page, or the callout fails.
Skipping this will result in "System.CalloutException: IO Exception:
Unauthorized endpoint, please check Setup->Security->Remote site settings.
endpoint ="...
13. SOAP Callout(wsdl2apex)
1. Collect the WSDL for the application that the salesforce is going to
consume.
2. Import the WSDL into Salesforce
Develop > Apex Classes > Generate from WSDL.
3. The successfully generated Apex class includes methods for calling the
third-party Web service represented by the WSDL document. Now create an
instance of the stub in your Apex code and call the methods on generated
Apex class.
Some free SOAP webservices with WSDL can be found :
http://www.actionscript.org/forums/showthread.php3?t=70742
14. WSDL Parsing Errors
There is a list of Supported WSDL Features listed:
http://wiki.developerforce.com/page/Apex_Web_Services_and_Callouts#Supported_WSD
Beyond those you can modify the source WSDL to get a reasonable level of
support. For example:
1. WSDL with multiple portType, binding, port are not supported in Apex so
do keep only respective PortType, binding and port before generating class
from WSDL.
2. Datatype “anyType” is not supported in WSDLs used to generate Apex
code that is saved using API version 15.0 and later, change the same to
“string”.
3. …......
15. SOAP Callout(Continued...)
The WSDL2Apex generated code supports HTTP Headers. For example, you can use
this feature to set the value of a cookie in an authorization header. To set HTTP
headers, add inputHttpHeaders_x and outputHttpHeaders_x to the stub.
Here's an example that sets input HTTP Headers:
docSample.DocSamplePort stub = new docSample.DocSamplePort();
stub.inputHttpHeaders_x = new Map<String, String>();
//Setting a basic authentication header
stub.inputHttpHeaders_x.put('Authorization', 'Basic
QWxhZGRpbjpvcGVuIHNlc2FtZQ==');
//Setting a cookie header
stub.inputHttpHeaders_x.put('Cookie', 'name=value');
//Setting a custom HTTP header
stub.inputHttpHeaders_x.put('myHeader', 'myValue');
....
16. SOAP Callout(Continued...)
Here's one that accesses output HTTP Headers information:
docSample.DocSamplePort stub = new docSample.DocSamplePort();
stub.outputHttpHeaders_x = new Map<String, String>();
String input = 'This is the input string';
String output = stub.EchoString(input);
//Getting cookie header
String cookie = stub.outputHttpHeaders_x.get('Set-Cookie');
//Getting custom header
String myHeader = stub.outputHttpHeaders_x.get('My-Header');
17. Testing SOAP Callout
Apex provides the built-in WebServiceMock interface and the
Test.setMock method that we can use to receive fake responses in a
test method for a SOAP callout.
Security
Authentication(Certificate 2way SSL)
Authorization(SessionID or OAuth 2.0)
Crypto class
EncodingUtil Class
18. Certificate
Server Certificate
Client Certificate
- Legacy Process
stub.clientCert_x = 'xyz....';
stub.clientCertPasswd_x = 'passwd'; // <<< Password for the keystore
-Salesforce Org
stub.clientCertName_x = 'Certificate Name'; // <<< Salesforce’s certificate name
When SFDC makes a call to a secured server, it first tries to see if the server has a
Server Certificate. If it does, then it sends the Client Certificate. If this Client
Certificate is accepted by the web server, then the communication is valid and the
data is sent to and fro between SFDC and the web server
19. Oauth 2.0
OAuth endpoints are the URLs you use to make OAuth authentication
requests to Salesforce.
You need to use the correct Salesforce OAuth endpoint when issuing
authentication requests in your application. The primary OAuth endpoints
are:
For authorization: https://login.salesforce.com/services/oauth2/authorize
For token requests: https://login.salesforce.com/services/oauth2/token
For revoking OAuth tokens:
https://login.salesforce.com/services/oauth2/revoke
All endpoints require secure HTTP (HTTPS). Each OAuth flow defines
which endpoints you need to use and what request data you need to provide.
-Web Server Agent Oauth
-User Agent Oauth
-Username Password Agent OAuth