Salesforce Integration Bootcamp Notes

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

Salesforce Integration

Bootcamp – Notes
Instructor: Aniket Kohale
Date: 13/05/2023

Salesforce Integration Bootcamp Schedule & Plan - https://bit.ly/3pktVs6


Note: All Notes will reference multiple resources from google and linkedin. In Today’s world Google is Sea of
Information So, All Informations reference from various contents.
1

What is Integration?
Integration is the process of connecting different softwares systems and applications
together through the use of API’s (Application Programming Interface). It allows
different systems to communicate and share information with others, making it easier
to access and use data across different platforms.

Integration Terminologies?
1. API
2. API Endpoint
3. API Call or HTTP Callout or REST Callout
4. Resource
5. API Request
6. API Responses & Types (JSON/XML)
7. API Response Codes
8. Payload
9. API Methods
10. Query Parameters
11. Authentication
12. Web Services (REST & SOAP)
2

● API - Application Programming Interface is what API stands for. API is a set of
definitions and protocols that allow technology products and services to
communicate via the internet.
● API Call - The API call is simply the process of sending a request to your API
after setting up the right endpoints. Upon receiving your information, it is
processed, and you receive feedback. By entering your login and password into a
website and hitting ‘enter’, you made an API Call.
● API Endpoint - An endpoint is the end of a communication channel. When APIs
interact with other systems, each touchpoint of interaction is considered an
endpoint. For Example, It could be a server, or a database where a resource lives.
● Resource - An entity that can be represented by a URI and can be accessed
through an API. Resources can be anything from data (such as a list of users or a
single user's profile) to operations (such as creating or updating a resource).
● Request - An HTTP request sent by a client to a server to retrieve or modify data.
A request typically includes a method, a URI, and a set of headers and/or a body.
● Response - An HTTP response sent by a server to a client in response to a
request.
● Response Code - A numerical status code ) returned in an API response to
indicate the success or failure of a request. Common response codes include
200 (OK), 404 (Not Found), and 500 (Internal Server Error).
● Payload - The data sent in an API request or response, often in the form of a
JSON object.
● Method - The HTTP verb used in an API request, such as GET, POST, PUT, or
DELETE.
● Query Parameters - Key-value pairs that are ) added to the end of an API
endpoint URL to specify certain criteria or filters for the data being requested.
● Authentication - The process of verifying the identity of a client or user before
allowing them to access an API. This is often done using an API key or other
form of credentials.
● JSON - (JavaScript Object Notation) is a lightweight data-interchange format
based on a subset of JavaScript programming language standards. JSON has
the advantage that it is both easy for humans to read and write and for machines
to parse and generate. It is a format that is completely agnostic to languages and
uses conventions that are familiar to programmers of C-family languages.
3

● Parameters - Parameters are special types of variables used in computer


programming to pass information between procedures and functions. An
argument to a function is referred to as a parameter. Adding three numbers, for
example, may require three parameters.
● REST - Created by Roy Fielding, a computer scientist, REST, which stands for
REpresentational State Transfer, is an application programming interface that
conforms to the constraints of REST architectural style and enables a quicker
interaction between different, RESTful web services. A stateless Web service
must be able to read and modify its resources using a predefined set of
operations and a textual representation.
● SOAP - Simple Object Access Protocol (SOAP) is a protocol specification for
exchanging structured information to implement web services. SOAP leverages
XML Information Set for message format and other application-layer protocols,
such as HTTP or SMTP for message transmission. The messaging services
provided by SOAP are exclusively XML-based. Microsoft originally developed the
SOAP protocol to replace old technologies such as Distributed Component
Object Model (DCOM) and Common Object Request Broker Architecture (CORBA)
that cannot work over the internet.

What is Web Services?


A Web Service is can be defined by following ways:

○ It is a client-server application or application component for communication.

○ The method of communication between two devices over the network.

○ It is a software system for interoperable machine to machine communication.

○ It is a collection of standards or protocols for exchanging information between


two devices or applications.

Let's understand it by the figure given below:


4
5

REST API Fundamentals

Source: www.liquidweb.com

● It is an architecture style to develop web applications. It uses HTTP Protocol as a


communication interface. Introduced by Roy Fielding in 2000.
● In a REST architecture, the client makes an HTTP request and data is sent as a
HTTP Response.
● REST API’s have a fixed set of endpoints, each representing a specific resource.
● Uses HTTP Methods to request data and Response based on the endpoint being
called.
● REST API’s are typically more rigid and require multiple requests to retrieve all the
data needed for a particular use case.
● Efficiency of an API depends on the specific needs of the client and the use case.
● REST API’s can be cached more easily, as the response from a specific endpoint
will always be the same. Note: While caching can improve performance, it can
6

also lead to outdated or state data being served to clients if the cache is not
properly invalidated or refreshed.
● REST API’s can sometimes suffer from over fetching or under fetching, where the
client receives more or less data than it needs.
● In a REST API, adding a new field or endpoint requires a new version of the API.
This makes API evolution harder. Must use versioning to ensure that the existing
clients do not break. Needs to be supported and maintained.
● REST API’s typically require versioning when the shape of the data changes. In a
REST API, versioning can be implemented by using a different URL for each
version of the API.

HTTP Protocol
● HTTP Protocol - HTTP stands for HyperText Transfer Protocol.
Communication between client and web servers is done by sending HTTP
Requests and receiving HTTP Responses. HTTP Protocol is used to
perform CRUD operations (Create, Read, Update, Delete) by sending HTTP
requests with different HTTP methods. HTTP methods are also called
HTTP verbs.

HTTP Request Structure


HTTP Request Structure - (Highlighted in purple) - Example URI
http://api.example.com/products?name=laptop&available=true

Every HTTP request should have a URL or URI address and a method. The format of a
request message includes - A request-line, Zero or more header field(s) followed by
CRLF (Carriage Return, Line Feed), An empty line, A message-body (optional)

HTTP Methods in REST


REST - REpresentational State Transfer. It is a set of architectural principles for
designing web services. Web services based on REST Architecture are known as
RESTful web services. REST makes it easy to share data between clients and servers.
7

REST applications use HTTP methods like GET, POST, DELETE, PUT, etc., to do CRUD
operations.

GET Method
POST Method
PUT Method
PATCH Method
DELETE Method

GET Method - A GET request is used to request information from a resource such as a
website, a server or an API.

Example:

GET /api/employees/{employee-id} - Returns a specific employee by employee id.

GET /api/employees - Returns a list of all employees.

Since the GET method should never change the data on the resources and just read
them(ready only), it is considered a safe method.

Test an API with a GET Method - When we want to test an API, the most popular
method that we would Therefore, We expect to use is the GET method.

- If the resource is accessible, the API returns the 200 Status Code, which means
OK.
- Along with the 200 Status Code, the server usually returns a response body in
XML or JSON format. So, for example, we expect the [GET] /members endpoint
to return a list of members in XML or JSON.
- If the server does not support the endpoint, the server returns the 404 Status
Code, which means Not Found.
- If we send the request in the wrong syntax, the server returns the 400 Status
Code, which means Bad Request.

POST Method - It Created a new resource on the backend server. We send data to the
server in the request body.

Example:
8

POST /api/employees/department - Creates a department resource.

POST /api/employees/232/department/114/department-items - Creates a department


item using the employee id and department id.

Test an API with a POST Method - Since the POST method creates data, we must be
cautious about changing the data. Testing all the POST methods in APIs is highly
recommended. Here are some suggestions that we can do for testing APIs with POST
Method

- Create a resource with the POST method, and it should return the 201 Status
Code.
- Perform the GET method to check if it created the resource was successfully
created. You should get the 200 status code, and the response should contain
the created resource.
- Perform the POST method with incorrect or wrong formatted data to check if the
operation fails.

PUT Method - Using this, we can update an existing resource by sending the updated
data as the content of the request body to the server.

Example:

PUT /api/employees/123 - Update employee by employee id

If it applies to a collection of resources, it replaces the whole collection, so be careful


using it. The server will return the 200 or 204 The PUT method is status codes after
updating.

Test an API with a PUT Method - The PUT method is about modifying the entire
resources. Make sure to do the following operations.

- Send a PUT request fo the server many times, and it should always return the
same result.
9

- When the server completes the PUT request and updates the resource, the
response should come with 200 or 204 status codes.
- After the server completes the PUT request, make a GET request to check if the
data is updated correctly on the resource.
- If the input is invalid or has the wrong format, the resource must not be updated.

PATCH Method - Similar to PUT, PATCH updates a resource, but it updates data partially
and not entirely.

Example:

PATCH /api/employees/123 - {“name” : “Brij”} - Updates name for employee id 123.

The PATCH method updates the provided fields of the employee entity. In general, this
modification should be in a standard format like JSON or XML.

Test an API with a PATCH Method - To test an API with PATCH method, follow the steps
for the testing API with the PUT and the POST Methods. Consider the following results

- Send a PATCH request to the server. The server will return the 2xx HTTP status
code, which means, the request is successfully received, understood, and
accepted.
- Perform the GET request and verify that the content is updated correctly.
- If the request payload is incorrect or ill-formatted, the operation must fail.

DELETE Method - The DELETE method deletes a resource. Regardless of the number of
calls, it returns the same result.

Example:

DELETE /api/employees/235 - Delete employee by employee id.

Most APIs always return the 200 status code even if we try to delete a deleted resource
but in some APIs, If the target data no longer exists, the method call would return a 404
status code.
10

Test an API with a DELETE Method - When it comes to deleting something on the
server, we should be cautious. We are deleting data, and it is critical. Then perform the
following actions

- Call the POST method to create a new resource. Never test DELETE with actual
data. For example, first, create a new employee and then fry to delete the
employee you just created.
- Make the DELETE request for a specific resource. For example, the request
[DELETE] /employees/{employee-id} deletes a employee with the specified
employee id.
- Call the GET method for the deleted employee, which should return 404, as the
resource no longer exists.

HTTP Status Codes


HTTP Status Codes - HTTP response codes are three-digit numbers that provide
information about the status of a request made to a web server. They help to indicate
whether the request was successful, and if not, why not. The Internet Assigned
Numbers Authority (IANA) is the organization responsible for maintaining the registry of
HTTP response codes. They define the codes and ensure that they are used
consistently across the internet.

HTTP Request Methods - HTTP defines request methods to the desired action for a
resource Here are the 5 important request methods:

- GET retrieves data from a specified resource.


- POST sends data to a server to create a new resource.
- PUT updates an existing resource with new data.
- DELETE removes a specified resource.
- PATCH applies partial modifications to a resource.
11

HTTP Status Codes

1XX Informational -

100 (Continue)
101 (Switching Protocols)
102 (Processing)
103 (Early Hints)

2XX Successful -

200 (0K)
201 (Created)
202 (Accepted)
203 (Non-Authoritative Information)
204 (No Content)
205 (Reset Content)
206 (Partial Content)
207 (Multi-Status)
208 (Already Reported)
226 (IM Used)

3XX Redirection -

300 (Multiple Choices)


301 (Moved Permanently)
302 (Found)
303 (See Other)
304 (Not Modified)
305 (Use Proxy)
306 (Switch Proxy)
307 (Temporary Redirect)
308 (Permanent Redirect)
12

4XX Client Error -

400 (Bad Request)


401 (Unauthorized)
402 (Payment Required)
403 (Forbidden)
404 (Not Found)
405 (Method Not Allowed)
406 (Not Acceptable)
407 (Proxy Authentication Required)
408 (Request Timeout)
409 (Conflict)
410 (Gone)
411 (Length Required)
412 (Precondition Failed)
413 (Payload Too Large)
414 (URI Too Long)
415 (Unsupported Media Type)
416 (Range Not Satisfiable)
417 (Expectation Failed)
418 (I'm a Teapot)
421 (Misdirected Request)
422 (Unprocessable Entity)
423 (Locked)
424 (Failed Dependency)
425 (Too Early)
426 (Upgrade Required)
428 (Precondition Required)
429 (Too Many Requests)
431 (Request Header Fields Too Large)
451 (Unavailable for Legal Reasons)
13

5XX Server Error -

500 (Internal Server Error)’


501 (Not Implemented)
502 (Bad Gateway)
503 (Service Unavailable)
504 (Gateway Timeout)
505 (HTTP Version Not Supported)
506 (Variant Also Negotiates)
507 (Insufficient Storage)
508 (Loop Detected)
510 (Not Extended)
511 (Network Authentication Required)
14

JSON Fundamentals using Apex


JSON Support

System.JSONGenerator

System.JSONParser

● System.JSON - Contains methods for serializing Apex objects into JSON format
and deserializing JSON content that was serialized using the serialize method in
this class.
● System.JSONGenerator - Contains methods used to serialize objects into JSON
content using the standard JSON encoding.
● System.JSONParser - Represents a parser for JSON-encoded content.

REST Callouts using Apex (HTTP Callouts)

HTTP and Callout Basics

REST callouts are based on HTTP. To understand how callouts work, it’s helpful to
understand a few things about HTTP. Each callout request is associated with an HTTP
method and an endpoint. The HTTP method indicates what type of action is desired.
15

HTTP Classes

These classes expose the HTTP request and response functionality.


● Http Class. Use this class to initiate an HTTP request and response.
● HttpRequest Class: Use this class to programmatically create HTTP requests like
GET, POST, PUT, and DELETE.
● HttpResponse Class: Use this class to handle the HTTP response returned by
HTTP.

The HttpRequest and HttpResponse classes support the following elements.


● HttpRequest
○ HTTP request types, such as GET, POST, PUT, DELETE, TRACE, CONNECT,
HEAD, and OPTIONS
○ Request headers if needed
○ Read and connection timeouts
○ Redirects if needed
○ Content of the message body
● HttpResponse
○ The HTTP status code
○ Response headers if needed
○ Content of the response body

Call Rest API From Apex Class - Sample Apex Code


16

public class HttpCalloutSample {

// Pass in the endpoint to be used using the string url


public String getCalloutResponseContents(String url) {

// Instantiate a new http object


Http h = new Http();

// Instantiate a new HTTP request, specify the method (GET) as well as the
endpoint
HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setMethod('GET');

// Send the request, and return a response


HttpResponse res = h.send(req);
return res.getBody();
}
}

Send Data to a Service


Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('EXTENRAL_REST_API_URL');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
request.setBody('{"ABC":"ABC"}');
HttpResponse response = http.send(request);

if(response.getStatusCode() != 201) {
System.debug('The status code returned was not expected: ' +
response.getStatusCode() + ' ' + response.getStatus());
} else {
System.debug(response.getBody());
}

Resources:

1. https://trailhead.salesforce.com/content/learn/modules/apex_integration_servic
es/apex_integration_rest_callouts
17

2. https://developer.salesforce.com/docs/atlas.en-us.224.0.apexcode.meta/apexc
ode/apex_callouts_http.htm
3. https://developer.salesforce.com/docs/atlas.en-us.224.0.apexcode.meta/apexc
ode/apex_classes_restful_http.htm

REST Services using Apex - Create Custom Rest API In Salesforce


Exposing Apex Classes as REST Web Services. You can expose your Apex classes and
methods so that external applications can access your code and your application
through the REST architecture.

Source: www.apexhours.com

Use Action

@RestResource(urlMapping=“url”) Defines the class as a


custom Apex endpoint

@HttpGet Defines the function to Read


be called via Http Get-
Used to retrieve a record

@HttpDelete Used to delete a record Delete

@HttpPost Used to create a record Create


18

@HttpPatch Used to partially update a Upsert


record

@HttpPut Used to fully update a Update


record

● Introduction to Apex REST


● Apex REST Annotations
● Apex REST Methods
● Exposing Data with Apex REST Web Service Methods
● Apex REST Code Samples

Here is an example of a custom Apex REST API in Salesforce.

@RestResource(urlMapping='/api/Account/*')
global with sharing class MyFirstRestAPIClass
{
@HttpGet
global static Account doGet() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
String AccNumber =
req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE
AccountNumber = :AccNumber ];
return result;
}

@HttpDelete
global static void doDelete() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
19

String AccNumber =
req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE
AccountNumber = :AccNumber ];
delete result;
}

@HttpPost
global static String doPost(String name,String phone,String AccountNumber )
{
Account acc = new Account();
acc.name= name;
acc.phone=phone;
acc.AccountNumber =AccountNumber ;
insert acc;

return acc.id;
}

Postman Tool
https://www.postman.com/downloads/ & https://www.postman.com/

Postman is one of the most popular software testing tools which is used for API testing.
With the help of this tool, developers can easily create, test, share, and document APIs.

This tutorial will help in understanding why Postman is so famous and what makes it
unique when compared to other API testing tools. All the examples in this tutorial are
tested and can be imported in Postman.

● Postman is a standalone software testing API (Application Programming


Interface) platform to build, test, design, modify, and document APIs. It is a
simple Graphic User Interface for sending and viewing HTTP requests and
responses.
20

● While using Postman, for testing purposes, one doesn't need to write any HTTP
client network code. Instead, we build test suites called collections and let
Postman interact with the API.

● In this tool, nearly any functionality that any developer may need is embedded.
This tool has the ability to make various types of HTTP requests like GET, POST,
PUT, PATCH, and convert the API to code for languages like JavaScript and
Python.

Important Links to Understand Postman Tool Working

1. Installation and Updates


2. Postman Navigation
3. Sending Your First Request
4. GET Request in Postman
5. Response in Postman
6. Request Parameters in Postman
7. POST Request in Postman
8. Creating Requests

● API and REST API Fundamentals - https://lnkd.in/e8eMet_k


● API Methods - https://lnkd.in/ey9v7-hU
● API Terminologies - https://lnkd.in/eRsPMzpd
● API Authentication - https://lnkd.in/eNPfpAdE
● API Status Codes - https://lnkd.in/egXizUrS
● REST API vs GraphQL - https://lnkd.in/eZHREdgC
● API Integration - https://lnkd.in/eDASPP5m
● API Testing - https://lnkd.in/emgmWJqH
● API with Python - https://lnkd.in/eM23ah2y
● API Scaling - https://lnkd.in/e3mZSvmn
● Designing and Developing Robust APIs - https://lnkd.in/eBXzbFyg
● Designing APIs with Postman- https://lnkd.in/ezue3d4B
● Testing APIs with Postman - https://lnkd.in/eCPnGTGi
21

Dummy Practice Live REST API’s

1) https://reqres.in/

2) http://dummy.restapiexample.com/

3) https://jsonplaceholder.typicode.com/

4) https://gorest.co.in/

5) https://restful-booker.herokuapp.com/

6) https://httpbin.org/#/

7) https://petstore.swagger.io/

8) https://fakerestapi.azurewebsites.net...

9) https://documenter.getpostman.com/vie...

10) Google API's - https://developers.google.com/maps/documentation

You might also like