0% found this document useful (0 votes)
49 views12 pages

Apex Integration Services Salesforce Notes

The document discusses integrating Salesforce with external data sources using Salesforce Connect and APIs, detailing how to create external objects and access real-time data. It explains various HTTP methods (GET, PUT, POST, PATCH, DELETE) and their characteristics, along with HTTP status codes and the differences between SOAP and RESTful web services. Additionally, it covers consuming and exposing web services in Salesforce, including the use of WSDL for SOAP and the process for making callouts to RESTful services.

Uploaded by

tretretre112
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views12 pages

Apex Integration Services Salesforce Notes

The document discusses integrating Salesforce with external data sources using Salesforce Connect and APIs, detailing how to create external objects and access real-time data. It explains various HTTP methods (GET, PUT, POST, PATCH, DELETE) and their characteristics, along with HTTP status codes and the differences between SOAP and RESTful web services. Additionally, it covers consuming and exposing web services in Salesforce, including the use of WSDL for SOAP and the process for making callouts to RESTful services.

Uploaded by

tretretre112
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

External Data and Salesforce Connect

Salesforce Connect

- We’re going to be talking about how we can integrate Salesforce orgs with external sources
- We can do so declaratively through Salesforce Connect
- Salesforce Connect lets us create external objects that map to tables in databases residing
outside of our org, so our org can work with data stored in multiple databases - all but one of
which will be external to our org
- Salesforce Connect allows us to access data in real-time
o This is great if we have a large amount of data in an outside system that we plan to
continue using and don’t want to upload it to our org because of storage reasons or just
for ease of use

APIs
- API stands for Application Programming Interface
- Server-side APIs are the part of the server that exposes endpoints to receive requests from a
client, parses them, tells the rest of the system what operations to perform, and then returns a
response from the server based on the result of those operations
- When we’re viewing webpages as end users, the underlying API interaction is abstracted from
us, but we’re still interacting with an API indirectly
- But many websites offer public APIs that developers can interact with programmatically
o These don’t APIs don’t return markup to be displayed (there’s no user interface
involved), rather they return data in different formats

Type of Webservice Data Formats


REST XML, JSON
SOAP XML

- APIs store resources (i.e. individual records) using Uniform Resource Identifiers (URIs)
o We can access URIs at their corresponding Uniform Resource Locator (URLs), which are
a part of the URI

HTTP Methods
- SOAP is built on top of HTTP and many REST services use HTTP as their communication protocol
- Three of the five HTTP methods we’ll talk about are idempotent
- Being idempotent means that the end result of a set of duplicate requests with the same
method to the same URL is independent of the number of duplicate requests made
o We CAN get different status codes in responses from idempotent methods (we’ll see
this shortly)
GET

- An idempotent method
- Used to retrieve the resource that stored with the target URI
- Because we’re only reading data - not changing it - it makes no difference if we make a GET
request once or 100 times

PUT

- Either creates a resource at the target URL or updates (read: overwrites) the entirety of the
resource at said UL if it already exists
- Any duplicate PUT requests to the same URL after the initial request will overwrite the resource
created in the first call
o Because there won’t be any dependence on the number of previous requests, PUT is
also idempotent

POST

- Lets us create a resource at the target URI or update an existing resource


- But POST requires us to send any update calls to a URL that’s different from the URL that we’ll
send a create request to
- So POST is not idempotent because duplicate requests to the same URL will have compounding
results
o The first POST operation will create one resource, the second will create a second
resource, etc.

PATCH

- Allows us to update parts of an existing resource, but doesn’t overwrite the entire resource
- When making a PATCH request, we only provide values for the fields that we want to change on
the existing resource
- Not idempotent

DELETE

- Idempotent
- The first DELETE call will delete the resource with the specified URI
- Because the resource no longer exists after the first DELETE call, we can make as many duplicate
DELETE requests as we want - the outcome of the operation is independent of the number of
duplicate requests
o Although subsequent DELETE calls will give different status codes in their responses

HTTP Status Codes


- When we make a request using an HTTP method, the server will return a status code along with
its response
- The status code indicates the outcome of the operation
- It will be a number between 100 and 599
- We can group status codes into five: 1xx, 2xx, 3xx, 4xx, and 5xx codes
- Each status code has an associated message and meaning

1xx HTTP Status Codes

- These codes are informational


- They indicate how the operation that our request invoked is going while it’s still being processed
- E.g.

Status Code Code Message Meaning


100 Continue No errors processing the
request so far.

2xx HTTP Status Code

- These codes indicate success

Status Code Code Message Meaning


200 OK The request was successful.
201 Created The resource was created. A
common response from PUT
and POST calls.
204 No Content The request was successful, but
the body of the response is
empty. A common response
from a DELETE call - some
services remove the resource
and return what they removed
in the response body, others
simply remove the resource and
continue on their way.

- We’ll frequently check for a 200 status code when we want to execute some logic as a result of a
successful call
3xx HTTP Status Codes

- These codes indicate redirects

Status Code Code Message Meaning


300 Multiple Choice There are multiple possible
responses to our request and
we should choose one of them.
301 Moved Permanently The resource’s URL has changed
and the new URL for the
resource is included in the
response body.
307 Temporary Redirect The resource’s URL has changed
temporarily and we should
make a request to the URL
included in the response body.

4xx HTTP Status Codes

- Client-side errors

Status Code Code Message Meaning


400 Bad Request Our request had a syntax error.
401 Unauthorized We must provide credentials to
perform the operation we’re
attempting.
403 Forbidden We provided credentials when
trying our operation, but they
didn’t give us authorization to
proceed.
404 Page Not Found The request was sent to a
nonexistent URL.

- 404 is the code that we’ll receive in response to duplicate DELETE requests - the first request
removed the resource, so its URL no longer exists when we make subsequent requests

5xx HTTP Status Codes

- Indicate server-side errors

Status Code Code Message Meaning


500 Internal Server Error The server encountered a
situation it didn’t know how to
handle when processing our
request.
502 Bad Gateway The server made a call to
another service to get the
information necessary for our
request, but that second service
gave an invalid response.

SOAP Webservices
- SOAP stands for Simple Object Access Protocol
- It’s an XML-based communication architecture that allows different platforms and languages to
communicate through HTTP requests
- SOAP services explain the ways to interact with them through WSDL (Web Service Description
Language), a language based on XML
- WSDL files quickly become verbose, so SOAP can be much less intuitive than REST
o But as we’ll see shortly, Salesforce offers a tool to help with this

Consuming SOAP Webservices


Consuming

- When we talk about consuming webservice, we mean that we’re interacting with an external
API and either retrieving or manipulating the data stored on the server that the API gatekeeps

WSDL2Apex

- Found in the Apex Classes page in Setup


o Once there, we click Generate from WSDL, upload our WSDL file, and click Parse WSDL
o Then we’ll choose the name for the Apex class that Salesforce is going to generate from
the WSDL and click Generate Apex Code
- This tool creates Apex classes based off of the WSDL we provide
o We can then call the methods within these classes to interact with the external SOAP
service instead of needing to parse the WSDL

Allowlisting

- Before we can make any request to an external site (doesn’t matter the kind of service), we
need to allowlist it in our org
- To do so, we navigate to the Remote Site Settings and click New Remote Site
- Once this is completed, we’ll be able to make an external callout to the service

Testing Callouts to SOAP Webservices

Mock Classes

- Apex test classes can’t make callouts to external services


- So when we’re testing any Apex that makes a callout, we need to create a response that mocks
the one we would get as a result of the actual request
- For SOAP callouts, we do this by making a second test class that implements the
WebServiceMock interface
- Then we’ll let the testing framework know which mock we’re using with the Test.setMock()
method
o This method takes two arguments
o The first is the type of interface our mock implements (WebServiceMock.class when
we’re testing SOAP callouts)
o The second is an instance of the class that implements this interface
- Mock classes must be global or public and define the doInvoke() method, which has a void
return type and is also public or global
- doInvoke() takes nine parameters, which are (in order):

doInvoke() Parameter Data Type Common Parameter Name


Object stub
Object request
Map response
String endpoint
String soapAction
String requestName
String responseNamespace
String responseName
String responseType

- within our doInvoke() method, we must populate the response_x key of the Map<String,
Object> parameter with an instance of the class indicated by the responeType parameter
- skeleton for mock class (first image) and test class (second image)
- in the mock class skeleton, we included some placeholders

Placeholder Replacement
AutoGeneratedClass The class created by WSDL2Apex
ResponseTypeResponse_element The class indicated by the value that the testing
framework passes to the responseType
parameter (which will likely end with
Response_element)
expectedMemberVar A member variable from the class corresponding
to responseType

- if we’re inserting test data at the beginning of a test method, we must perform the DML
operation, then call Test.startTest(), Test.setMock(), make the mock callout, and call
Test.stopTest(), in that order

Exposing Apex Code as a SOAP Webservice


Exposing Code

- when we talk about exposing our code as a webservice, we are the API
o we’re allowing external services to interact with our data through the ways we define

Code Requirements

- we can expose Apex code as a SOAP webservice as long as the class is global and any exposed
methods within the class are static and use the webservice keyword
- webservice is used in place of an access modifier

Generating the WSDL

- we do this by navigating to the Apex Classes and clicking the WSDL link next to our desired class
o this link will take us to a webpage holding our WSDL
o then we can save the webpage as an XML file and distribute to anyone that we want to
be able to interact with our service
o then the people with the WSDL can consume through an application like SoapUI and
start making calls to our code

Considerations

- any exposed method will run in the context of the system by default
- so we should implement Apex to enforce object, field, and/or record level permissions
- the webservice keyword cannot be used on any outer classes
- we can expose class member variables with webservice, but we don’t mark these as static
- writing tests for an exposed class isn’t different from writing tests for any regular class - we call
the class’s methods from our test class and follow testing best practices

The Salesforce SOAP API

- Salesforce has a standard, out-of-the-box (oob) SOAP API that we can use
- It allows us to find duplicate records, execute queries, get information about objects and fields,
perform DML operations, deploy and retrieve metadata, and more
- To use it, we navigate to the API page in Setup and click Generate Enterprise WSDL (for us to
use) or Generate Partner WSDL (for other Salesforce orgs to use)

RESTful Webservices
REST

- REST stands for Representational State Transfer


- It’s a set of guidelines for API architecture that includes requirements like implementing a
uniform interface across the service and the server being stateless
o When the server is stateless, each request can operate independently without any
context from previous requests stored on the server
o The server can’t store context (like an endpoint) from previous requests, but a stateless
server can of courses handle adding data to the related database that can then be
retrieved by subsequent requests
- Generally speaking, interacting with RESTful services is much more straightforward than
interacting with SOAP webservices

Consuming RESTful Webservices in Salesforce


Making the Callout

- Of course, we’ll have to allowlist any external sites before we can make a callout to them
- The process of writing the code is actually pretty short using the built-in HTTP classes
- Skeleton:

- We start by instantiating the Http and HttpRequest classes


- Then we use the setEndpoint() and setMethod() methods from the HttpRequest object to
specify the URL that our request is going to and the HTTP method we’re using, respectively
o HttpRequest has other setters, including setBody() and setHeader()
 We’ll use these if we want to specify a request body or if we need to
authenticate, respectively
- Once the setup is done, we make the request using the send() method from the Http class,
passing the HttpRequest object as an argument and assigning the response to an instance of the
HttpResponse
- We can check our response’s status and retrieve its body using the getBody()
o This body will almost always be JSON that we’ll have to parse
o Parsing JSON in Apex isn’t always intuitive, but we can use the
JSON.deserializeUntyped() method to convert the JSON to an Apex object
o Still, we’ll probably have to perform multiple type conversions
o The best method is trial-and-error by debugging every step we take to make sure we’re
on the right track
- Callouts (whether to SOAP or REST services) made from Apex are only asynchronous if the class
making them implements asynchronous Apex

Testing Callouts to RESTful Webservices


Mocking

- Like we saw before, Apex test classes can’t make callouts to external systems
- So we’ll have to make a mock response again, which we can do by
o Using a static resource
o Writing an Apex class that implements the HttpCalloutMock interface

Mock Class

- Skeleton

- When we implement the HttpCalloutMock interface, we need to provide a definition for the
respond() method
o This methods takes a single parameter of type HttpRequest and returns an
HttpResponse object
o We use the setHeader() method to specify our response format (JSON)
o We create the response body with setBody()
 We want to make sure that we make a key-value pair for every key the code
that we’re testing expects
o We set the status code with setStatusCode() and finish by returning the response
- We’ll then call Test.setMock() in our test class, the first argument will be the
HttpCalloutMock.class this time
o E.g. Test.setMock(HttpCalloutMock.class, new ExRESTCalloutMock())

Static Resource Mock

- To mock using a static resource, we’ll upload a JSON file as a resource


- Then we’ll write something like the following skeleton

- We create an instance of the StaticResourceMock class, set the static resource we’re using, our
response status code, our response format, and invoke Test.setMock()
o Note that the first argument to Test.setMock() is still HttpCalloutMock.class, even
though we haven’t written a mock class
- Just like with SOAP callouts, if we’re doing any setup DML within the test method, we need to
follow it with Test.startTest(), then Test.setMock(), a call to the method that makes the callout,
and Test.stopTest()

Exposing Apex Code as a RESTful Webservice


Code Requirements

- We can expose custom Apex classes as REST APIs so long as the class is global and annotated
with @RestResource
o In parentheses following the annotation, we set the urlMapping parameter, passing the
relative URL we want our API to live at
o This URL is relative to our Salesforce instance, and /services/apexrest, which itself
follows our instance URL
- Within the class, we can expose methods by declaring them as global and static
o We’ll also annotate them with the corresponding Http method annotation
 This can be @HttpGet, @HttpPost, @HttpPut, @HttpDelete, or @HttpPatch
 GET and DELETE methods shouldn’t take parameters
 We can only use each annotation a maximum of one time per class
- Our exposed methods will run in system context by default, so we’ll need to implement Apex
security
- We test exposed code just like we test any other Apex code

The Salesforce REST API


- Salesforce also has a standard REST API they provide
- We can use it to execute queries, get information about objects and fields, perform DML
operations, deploy and retrieve metadata, and more

Other OOB Salesforce APIs


Bulk API

- Accepts data in either JSON, XML, or CSV formats


- Lets us import or delete large amounts of records asynchronously

Chatter REST API

- Lets us synchronously access Chatter feeds/posts and create Chatter posts


- Transmits data in XML or JSON
User Interface API

- Lets us mimic the Salesforce UI


- Communicates synchronously in JSON

Analytics REST API

- Lets us synchronously interact with Einstein Analytics through JSON or XML

Tooling API

- We can communicate with this through a REST or SOAP architecture


- Synchronous
- Uses JSON or XML data formats
- Used to create custom development tools, such as IDEs or deployment scripts, for Salesforce
- Also lets us access our org’s metadata

Metadata API

- A SOAP-based API that asynchronously communicates through XML


- We can use it to retrieve or deploy metadata

Streaming API

- Communicates through a Bayeux protocol using JSON


- Asynchronous
- Used to subscribe notifications about changes to Salesforce records or the execution of custom
events

You might also like