why use force.com api?
To connect things and automate things so that it can be more productive with salesforce platform.
1.Connect stuff
Build systems that span applications,cloud and on-premises.
2.Automate stuff
Reduce manual effort and establish consistent operations.
Force Integration Patterns :
==============================
we have Four Integration patterns
1.RPC (Remote procedure call) - Request and Reply
salesforce is invoking a process on the remote system and waiting for the response.
2.RPC (Remote procedure call) - Fire and Forget
salesforce is invoking something in the remote system, but it's doesn't wait for the response.it's asynchronous.
3.Batch Data sync
pulling data into salesforce or pushing data out with bulk data on a schedule or a regular rhythm.
4.Remote call In
external systems calling into salesforce to grab data, create records, update records and delete records.
Request and Reply :
===================
1.Synchronous call to remote system.
2.Initiated by event or batch (Apex triggers and Apex batch classes)
3.Require idempotency and duplicate check
It's important to ensure that the remote procedure being called is idempotent,otherwise repeatedly calling the same message can have
different results and can result in data integrity issues.Also, duplicates before inserting must be checked if an operation create records on the external system.
ex :
GET,PUT,DELETE (Idempotent)
POST (Non-idempotent)
4.Careful security.
Any call to a remote system must maintain the confidentiality,integrity and availability of the request.
1.Two-way SSL can be used to maintain authenticity of both the client and server.
2.Consider using digital signatures using the Apex Crypto class methods to ensure request integrity.
3.Appropriate firewall mechanisms should always be implemented to protect the external system.
Fire and Forget :
=================
1.Asynchronous call to remote system.
salesforce doesn't wait for the completion of the process.
ex : Outbound messaging through workflow.
2.Initiated by user or system event.
Apex triggers and apex batches
Note : In Fire and Forget, I am sending a message off and maybe it got there,maybe it didn't .I don't know for sure that it reached it because I'm(salesforce) not
waiting to get that acknowledgment in the same way.
3.Security considerations
Two-way SSL can be used together with the salesforce outbound messaging certificate though,one-way SSL is enabled by default.
Whitelist Salesforce server IP ranges for remote integration servers.
c.Appropriate firewall mechanisms should be implemented to protect the remote system.
Batch Data synchronization :
============================
1.Import and export large amount a of data.
2.Initial or ongoing load
3.optimize refresh schedule.
4.Consider post processing
5.Avoid contention
Remote call -in :
=================
1.External system interacts with salesforce.
2.Consider source system characteristics.
3.choices based on data volume.
Force.com's Integration-Related services:
=========================================
REST API
SOAP API
Lightning Connect
Data Loader
Bulk API
Platform Cache
External Objects
Streaming API
Outbound Messaging
Apex Callouts
SOAP API :
========
SOAP protocol access to salesforce data and functionality.
Using the Force.com SOAP API to Integrate with Enterprise APPS.
you're posting to one endpoint whether you're getting data or putting data or retrieving or updating,deleting,you're always posting.
When do you Use it ?
when i want to point my code language or code tools to a particular WSDL and generated some strongly typed objects that know how to talk with that , that is convenient,and it can be convenient to enterprise to enterprise apps that want to work with it or for developers who don't want to deal with
raw HTTP messages.
when i want to access the most functions, whether it's accessing things around users or around objects or around metadata.
1.SOAP API is enterprise friendly.
2.Broad coverage of UI capabilities.
you are not just dealing with objects, but dealing with resetting passwords or sending emails or doing all kinds of other things in salesforce,you have a lot of functionality in the SOAP API.
3.multiple WSDL interfaces
a. Enterprise WSDL
b. Partner WSDL
4.xml-based
Note :
serverUrl,sessionId
these two are important for subsequent requests.
SOAP API WSDL :
==============
1. Enterprise WSDL
2. Partner WSDL
Enterprise WSDL :
================
1.strongly typed .
Note : so every built in standard or custom object gets represented in that WSDL, even any custom
sort of operation,things like that,that WSDL is meant to be a representation of your organization,your account.
2.Easy to use
just reference that WSDL,generate some code,call it.
3. standard,custom objects
standard and custom objects shows up in that WSDL.
4.Best for single org solutions
Partner WSDL :
=============
1. weakly typed
you're dealing with the raw sobject,which is really the underlaying type of every object,and so you're dealing with it as an sobject type.
2.Flexible to use
3.describeSobject() for details
you can call that describe API to actually find out what objects are in there,and then be using this weakly typed things
4.Best for apps targeting multiple orgs.
Server URL's for the various APIs :
===================================
1.Enterprise API
https://server-api.salesforce.com/services/Soap/c/45.0/orgId
2.Partner API
https://server-api.salesforce.com/services/Soap/u/45.0/orgId
3.Metadata API
https://server-api.salesforce.com/services/Soap/m/45.0/orgId
4. Apex API
https://server-api.salesforce.com/services/Soap/s/45.0
5. Tooling API
https://server-api.salesforce.com/services/Soap/T/45.0/orgId
what are SOAP Objects ?
1.Objects represent database tables.
2.Records are like database rows
3.Multiple types of objects.
a. standard objects
b. custom objects
c. external objects
Data types :
=============
1.Primitive types
2.Field types
3.Compound fields
4.system fields
5.Required fields
6. field properties
Compound fields :
================
A set of fields that represent one thing. The compound field itself is readonly.
relationships :
==================
Master-detail (1:n)
Many to many
Lookup ( 1: n)
Types of SOAP API Calls :
==============================
1.core calls
core calls dealing with sobjects really,create ,delete ,get deleted, where you can pull everything that's been deleted from a preset time ,get all the updated things ,invalidate the sessions,
log in,log out , merge records, query records, query all the records ,which include things like that have been deleted , retrieve things based on an individual ID, search, update ,upsert.
2.Describe calls
describe all the tabs, describe the app menu , describe all the quick actions avaialable, describe global, all the objects in my org or describe the layout , which gives me all the page layouts for a particular object,describe an sobject.
so these are things that are almost metadata driven ,they're telling me about that user's experience, they're telling me about my org, they're telling me about my objects.
3.Utility calls
These are things the API or your client can call to obtain system timestamps, user information, change user passwords, send emails, all those sorts of things.
ex :
<urn:query>
<urn:queryString> SELECT Id,Name from Account</urn:queryString>
</urn:query>
utility call to get server time stamp put the below tag in body and sent to salesforce you will get server time stamp.
ex : <urn:getServerTimestamp/>
Handling faults :
=================
API Fault Element with Exception Code.
when you get faults back from salesforce , from the soap api, you get back a fault element with an exception code.so you get back an actual element in the SOAP payload, you're not getting back an HTTP error,you're actually getting back a fault within the message itself.
ex :
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<soapenv:Fault>
<faultcode>soapenv:Client</faultcode>
<faultstring>Element {urn:partner.soap.sforce.com}convertedStatus invalid at this location</faultstring>
</soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>
The soap fault element must appear as a body entry and must not appear more than once within a body element.
Error with Status code
Resolution Handled Client Side
Mru(most recent update) Header API call :
=============================
SOAP Header called mruUpdate is used to update most recent update record in the Recent Item Section.By default false.
If you want to see the recent record in the recent item section then you need to sent that flag to TRUE.
<urn:MruHeader>
<urn:updateMru> true</urn:updateMru>
</urn:MruHeader>
if you want to import bulk of records through SOAP and i don't want to just pollute that feed lot of information
Custom SOAP Service :
=======================
ex :
global class SoapVoterService{
webService static Voter__c getVoter(String voterId){
Voter__c voter = [SELECT ID,Name FROM Voter__c WHERE ID = : voterId];
return voter;
}
}
invoke service :
https:na30.salesforce.com/services/Soap/class/SoapVoterService
API Limits :
=============
1.you can have 10 concurrent queries per user, so you can have 10 query cursors open
at the same time.
2.you can have 25 concurrent calls in a production org of 20 seconds or longer,
so 5 in a dev edition,25 in a production and sandbox account.
3.you can do a 1 million daily API calls in a production organization.
4. 200 maximum records in a create or update request,keeping that in mind and even a 50 MB maximum request size.
Monitoring API Usage :
================
There are 3 way you can analysis the API Usage
- Last 24 hours usage
- Notification for API Usage
- API Usage Report
API Usage Report :
==============
Copy and append “/00O?rt=104” URL with your domain URL then you will see the “API Calls Made Within Last 7 Days” report.
REST API :
=========
The REST API is simple access to salesforce data and functionality
via RESTful endpoint.
REST where you're hitting different endpoints for different
resources.
Note :
1.Mobile,web friendly
2.Supports composite operations.
3.Standard interface
4. xml and json supported
Salesforce does use the OAuth protocol to allow users of these diferent apps
to securely access that data without having to give up their username
and password.
To authenticate the OAuth you have to create this connected app that defines
your application's OAuth's settings for your specific Salesforce org.
1.OAuth 2.0 User Agent Flow
These apps often use a scripting language,such as javascript,running within the browser.
This flow uses the OAuth 2.0 implicit grant type.
2.OAuth 2.0 Web Server Authentication Flow
server must be able to protect the client secret.
This flow uses an OAuth 2.0 authorization code grant type.
3.OAuth 2.0 JWT Bearer Token Flow
The main use case of the JWT Bearer Token Flow
is server-to-server API integration.This flow uses
a certificate to sign the JWT request and doesn't
require explicit user interaction.
4.OAuth 2.0 SAML Bearer Assertion Flow
An app can also reuse an existing authorization by
supplying a signed SAML 2.0 assertion.
5.SAML Assertion Flow
This flow is an alternative for orgs that are using
SAML to access Salesforce and want to access the web services API in the same way.
6.OAuth 2.0 username and Password Flow
Use it only for testing, when a user is not present
at app startup.In these cases, set user permissions to minimize
access and protect stored credentials from unauthorized access.
7.OAuth 2.0 Refresh Token Flow
8.OAuth 2.0 Device Authentication Flow
Command-line apps or applications that run on devices with limited
input and display capabilities such as TVs,appliance and other IOT devices,
can use this flow.
9.OAuth 2.0 Asset Token Flow
This flow combines issuing and registering asset tokens for efficient token
exchange and automatic linking of devices to service cloud asset data.
Web Server Flow :
===================
1.Client app directs user to salesforce authorization endpoint.
2.User logs into salesforce page with their credentials.
3.If successful login,user routed to callback URL with authorization code.
4.Client app sends authorization for access token.
5.Salesforce returns an access token, refresh token , and instance URL.
6.Application uses the access token to access salesforce data.
User-agent Flow :
=================
1.Client app directs user to salesforce authorization endpoint.
2.User logs into salesforce page with their credentials.
3.If successful login, user routed to callback URL with access token,more.
4.Application uses the access token to access Salesforce data.
Username - Password Flow :
==========================
1. Client app requests token using username and password.
2. Salesforce verifies credentials and
returns access token and insatnce URL.
3.Application uses the access token to
access Salesforce data.
ex :
create connected App
Consumer Key
Consumer Secret
Call back URL :
Depending on which OAuth flow you use. Callback URL
is typically the URL that a user's browser is redirected
to after successful authentication.
https://login.salesforce.com/services/oauth2/token
grant_type
client_id
client_secret
username
password
you will get back these payloads
access_token
instance_url
id
token_type
issued_at
signature
Types of REST API Calls via Standard Interface
core calls
Describe calls
Utility calls
The idea of core calls, getting sobject rows,
creating and updating records,querying,processing
rules and approvals,searching,composite operations,
all those things are kind of core calls working
with the core objects within salesforce.
Describe calls :
================
i can describe an sobject.
i can describe global, which gives me back all objects.
i can get layouts or tabs or themes.
switching between xml and json :
==================================
Append .xml or .json to the URI
For more complex , i could choose to
use the accept header,to get either text xml
or text json.
Three types of composite calls
1.batch up a set of operations.
2.create nested records.
3.create a set of unrelated records.
batch query :
============
https://na30.salesforce.com/services/data/v35.0/composite/batch
nested records :
===============
https://na30.salesforce.com/services/data/v35.0/composite/tree/Precinct__c
Custom REST API:
=================
@RestResource(urlMapping='/VotersWithDonation/*')
global class CustomVoterDonationService{
@HttpGet
global static VoterDonation GetVoter()
{
// get voter Id from request
RestRequest request = RestContext.Request;
String voterId = request.requestURI.substring(request.RequestURI.lastIndexOf('/')+1);
Voter__c voter = [SELECT ID,Name,Political_Party__c FROM Voter__c where ID = : voterId];
VoterDonation vdon= new VoterDonation();
vdon.VoterName = voter.Name;
vdon.VoterParty = voter.Political_Party__c;
// donation list
vdon.Donations = [ select Candidate_Name__c,Amount__c,Donation_Date__c FROM Voter_Donation__c Where
voter__r.ID = : voterId ];
return vdon;
}
global class VoterDonation{
String VoterName {get;set;}
String VoterParty {get; set;}
List<Voter_Donation__c> Donations {get;set;}
}
}
Bulk API :
============
1.Bulk loading of data.
2.Issue bulk queries
3.Asynchronous processing.
Programmatic access to quickly load into,
and retrieve data from salesforce.
Note :
when do you use it ?
Data synchronization between systems.
one -time data loads
Transferring significant number of records.
Lifecycle of a bulk api interaction :
=====================================
1.create job
2.add batches
3.close job
4.check status
5.retrieve results
Note :
========
Batch processing doesn't wait for closure
Jobs deleted after 7 days,regardless of status.
Batch :
=========
Batch is a set of records sent via an
HTTP POST.
Each Batch is processed independently by the server,
not even necessarily in the order received,you're
not guaranteed it's going to be in a
particular order.
1. A batch can be queued,meaning the process hasn't
actually started yet.
2.A batch can be inprogress,meaning it's processed.
3.if the job is aborted, this batch will still complete.
4.it can be in a completed state , that means that
processing is done.
Bulk API Limits :
===================
1. 10 minutes to process a batch
2. 5,000 Batches per rolling 24 hour period
3. 10,000 Maximum record count per batch
4. 10MB Max size for single CSV or XML file
Outbound messaging for Real-time Push Integration :
===================================================
Outbound Messaging :
===================
React to data changes by triggering
messages to Internet - facing endpoints.
Event-driven messaging
Asynchronous,but reliable delivery
Receiver is Internet - accessible
Note :
=======
1.Triggered by workflow rules based on
field changes.
2.Message reliably sent to endpoint.
3. Listeners implement WSDL
4.Support for callbacks
When do you use it ?
1.Replace polling-based solutions.
2.Create real - time ,responsive cloud systems.
3.Trigger business activities.
Securing Outbound Messaging Solutions :
=======================================
1. SSL/TLS endpoint
2.whitelist Salesforce IP addresses in client listener
3.validate against Salesforce Certificate.
Flow for Creating Outbound Messages :
=====================================
1.Create Outbound Message
2.Choose sObject
3.Set name,endpoint URL
4.Choose fields to send
5. Save Outbound Message
6. Associate with workflow rule.
Tracking Outbound Messages :
===========================
1.View items queued for delivery.
2.Observe any failures
3. Edit or delete items in the queue
4. Manually retry or wait for automatic interval.
Streaming API :
===============
Receive a live stream of data changes
based on an SOQL query that you define.
Event-driven messaging
Asynchronous, but not reliable delivery.
Receiver can be behind the firewalls.
Note :
1. "Topics" based on SOQL queries
2. Client(s) subscribe to "topics"
3. Poll ,not push
4. No guaranteed delivery,ordering.
When do you use it ?
1.Replace custom polling-based solutions.
2.Scale data events to multiple recipients.
Bayeux and CometD :
====================
1.Bayeux is a protocol for async messaging.
2.CometD is event bus, implementing Bayeux.
3. Uses long polling, WebSockets in 3.0.
4. Salesforce uses CometD 2.0
Implements : connect,disconnect,handshake,
subscribe,unsubscribe.
Authenticating Streaming API Users :
====================================
1.can use SOAP session ID
2.can use OAuth token
3.User,object,field security applies
Push Topics :
================
1.Record relates to CometD channel.
2.Notifications generated on record match.
3.Developer controls record match criteria.
4.Can deactivate or delete PushTopics.
5.One entity per query
6.Fields specified make up body of notification.
7.Changes take effect immediately.
8.Support for standard and Custom objects.
9. Basic subset of SOQL available.
Note :
semi-joins,anti-joins,aggregate queries,
count limit,relationships,order by,group by,
compound address are unsupported.
Notification rules :
===================
1.NotifyFor OperationCreate
2.NotifyFor OperationUpdate
3.NotifyFor OperationDelete
4.NotifyFor OperationUndelete
5.NotifyFor Fields
Note :
you have a few different options for what sort
of field should i be looking for, all of them,
referenced fields, select fields, where fields,
that will determine kind of which one
i'am checking to figure out, to trigger these events.
ex :
PushTopic pushTopic = new PushTopic();
pushTopic.Name ='UpdatedDonations';
pushTopic.Query = ' SELECT Id,Name,Amount__c,Donation_Date__c FROM voter_Donation__c';
pushTopic.ApiVersion = 35.0;
pushTopic.NotifyForOperationCreate = false;
pushTopic.NotifyForOperationUpdate = true;
pushTopic.NotifyForOperationUndelete = false;
pushTopic.NotifyForOperationDelete = 'Referenced';
insert pushTopic;
query :
=========
SELECT id,name from PushTopic
List<PushTopic> pts = [SELECT Id FROM PushTopic WHERE Name='UpdateDonations'];
pts[0].NotifyForFields = 'All';
Database.update(pts);
ex :
PushTopic pushTopic = new PushTopic();
pushTopic.Name ='AllDonations';
pushTopic.Query = ' SELECT Id,Name,Amount__c,Donation_Date__c FROM Voter_Donation__c';
pushTopic.ApiVersion = 35.0;
pushTopic.NotifyForOperationCreate = true;
pushTopic.NotifyForOperationUpdate = true;
pushTopic.NotifyForOperationUndelete = true;
pushTopic.NotifyForOperationDelete = true;
pushTopic.NotifyForFields ='Referenced';
insert pushTopic;
Generic Streaming :
===================
1.Send notifications on general events
2. Send events through REST endpoint
3. Can target subset of subscribers.
Streaming Channel : /u/notications/DemoGenericChannel
select Id, Name FROM StreamingChannel;
Streaming API Limits :
======================
1.50 (for enterprise)Topics per organization,up to 100
depending on your account type.
2.The maximum number of client subscribers per topic
is 1000 for enterprise, up to 2000 if you
have the performance or unlimited account.
3. The maximum number of events per day,any sort of
24 hour period, is 2,00,0000 (200k)
4. Maximum generic streaming events per day is
10,000(10k).
Apex Callouts :
=================
Make a call from Apex code to an external
web service and receive a response.
Note :
Aggregate Salesforce and external data
Create VisualForce pages based on data
from other systems.
Doing long-running async queries
Salesforce doesn't allow any DML operation
before a callout in the same transaction.
or
Typically not allowed after DML operations in the same transaction.
Remote Site Settings :
======================
1.Register/authorize external sites.
2.provide name,URL
3.can disable SSl
Named Credentials :
===================
1.Separate code from URL,authentication.
2.Use same code for different environments.
3.Anonymous,Basic or Oauth supported.
4.Use merge fields for custom authentication.
you can use merge fields if you want to do a
custom authentication or authorization scheme.
Long Running callouts in VisualForce :
======================================
1.User perceives faster response
2.Continuation server manages callout requests.
3.Make calls simultaneously,or through chaining.
Callout Limits :
================
20 concurrent callouts within an organization.
10/120 Default seconds for a timeout,maximum seconds for a timeout
100 Maximum callouts in a single transaction.
No comments:
Post a Comment