Integrating with Salesforce (Part 1)

Salesforce is a service first platform and it is often required to integrate Salesforce with external applications and services. In this episode we will learn about performing callouts to external services using Apex. Join us as you embark on this wonderful journey to become a champion Salesforce developer.

Most importantly don’t break a leg if you are overwhelmed with the pace of the live sessions. All Apex Hours for Student sessions will be recorded and will be available on our YouTube channel.

Here is some keynote from our session

Authentication

  • User Authentication
    • Username / password
    • Password never expires for API user
    • Profiles based restrictions
    • API only user
    • Limits on number of failed attempts
  • Authorization – OAuth
  • Data Security
    • How is access to data regulated?
  • Network Authentication
    • Login hours and IP ranges
    • Org-wide trusted IP Address List
    • Security Token for login via API or client outside white-listed IP range
  • Make sure the profile of the integration user meets the needs.

Authentication

  • Apex ignores security
  • Session Timeouts
  • Transport Security
    • SSL provides secure transport over HTTPs
  • Outbound
    • Two-way SSL
    • Port Restrictions
      • Port 80, 443, 1024-66535
    • Remote Site Settings
      • Sites which can be invoked from Salesforce

API

  • Application Programming Interface
  • Set of functions and procedures allowing the creation of applications that access the features or data of an OS, application, or other service.
  • Set of specifications, such as Hypertext Transfer Protocol (HTTP) request messages, along with a definition of the structure of response messages, usually in an Extensible Markup Language (XML) or JavaScript Object Notation (JSON) format
  • For example, Twitter’s REST API allows developers to access core Twitter data and the Search API provides methods for developers to interact with Twitter Search and trends data.

Basics of JSON

  • JSON Stand for “JavaScript Object Notation”.
  • Recommended for devices with low processing power or slow internet
  • It is language Independent representation of objects
  • Text based, human readable data exchange format
  • Parsers available in many languages
  • JSON can be transmitted over http / https
{
  "FirstName" : “Apex",
  "LastName" : “Hours"
}

JSON to Apex

Json To Apex

JSON to Apex Deserialization

String jsonString = ‘{"FirstName" : “Apex","LastName" : “Hours"}’;
Student st = (Student) System.JSON.deserialize( jsonString , Student.class);

Basics of XML

  • XML stands for eXtensible Markup Language like HTML
  • XML tags are not predefined. You need to define your customized tags.
  • Well, the structured format is easy to read and write from programs.
<student>
  <firstname>Apex</firstname>
  <lastname>Hours</lastname>
</student>

JSON Vs XML

JSON XML
JavaScript Object Notation has a type like String, number, Object, Boolean Extensible markup language is type less, and should be string
It is a way of representing objects It is a markup language and uses tag structure to represent data items
Retrieving value is easy Retrieving value is difficult
It does not provide any support for namespaces. It supports namespaces.
It is less secured It is more secure than JSON
Guidelines: Key – Enclosed in double Quotes(String) Value – Can be any datatype {} – Object [] – Array , – Separates data element within Object Guidelines: Element – <lastname>hours</lastname> Element Definition: <xs:element name=”lastname” type=”xs:string”/> Attribute – <lastname lang=”EN”>Smith</lastname> Attribute Definition – <xs:attribute name=”lang” type=”xs:string”/>

Which API Do I Use?

API Name Protocol Data Format Communication
REST API REST JSON, XML Synchronous
SOAP API SOAP (WSDL) XML Synchronous
Chatter REST API REST JSON, XML Synchronous (photos are processed asynchronously)
Analytics REST API REST JSON, XML Synchronous
Bulk API REST CSV, JSON, XML Asynchronous
Metadata API SOAP (WSDL) XML Asynchronous
Streaming API Bayeux JSON Asynchronous (stream of data)
Apex REST API REST JSON, XML, Custom Synchronous
Apex SOAP API SOAP (WSDL) XML Synchronous

REST API

  • Representational State Transfer is a style of software architecture for distributed hypermedia systems.
  • REST API has a lightweight request and response framework
  • Simple, easy to use and powerful web service based on RESTful principles.
  • Expose functionality via REST resources and HTTP methods.
  • (CRUD) records, search or query your data, retrieve object metadata, and access information about limits in your org.
  • REST API supports both XML and JSON.
  • Mobile and Web apps
  • Rest resource is referenced using URI, abstraction of information, access using HTTP methods
REST API

HTTP Methods

Method Action Details
HEAD Retrieve resource metadata
GET / @HttpGet Read Reads or retrieves records
POST / @HttpPost Create Creates records
PATCH / @HttpPatch Update Update fields in existing records
PUT / @HttpPut Upsert Update existing or create records
DELETE / @HttpDelete Delete Deletes records

Recording

Basic of Integration in Salesforce

Agenda

  • Web Communication Fundamentals
  • Understanding REST Vs SOAP
  • Message Exchange Formats – XML & JSON
  • Performing Callouts to External Services
    • HTTP Request & HTTP Response
  • Q & A
YouTube video

Basic of REST API, HTTP Method, Calling YouTube REST API from Salesforce

YouTube video

Assignment

Complete below assignment to win $1000 Salesforce VoucherClick here for rule.

Make Call-out to SmartyStreets API

SmartyStreets API is used to verify the address. In this milestone you need to consume https://smartystreets.com/products/apis/us-street-api

Requirement – The business ask is to verify the address of the event. Use the above API to verify the address & update “Location Verified” field on Event.

Must Have – Use of Error Handling and code re-usability

Don’t forget to register for our next session on Part 2. Check this post for all other session detail.

Please subscribe our YouTube channel to get notification for video upload.

So, learn at your pace and free will and ace your journey to Salesforce!

Jigar Shah
Jigar Shah
Articles: 15

24 Comments

  1. Thank you so much for all the sessions…I’m learning a lot. I’m the one that has been asking about sql server integration. sql server database is actually running on AWS and I need that sql server to send data to salesforce and either create sf records or update them. Similarly, I need SF to send data to sql server to update records, never create on sql server. sql server database is the master. I currently use an ETL tool but it is very expensive and I want to use custom code to get this done. I’m confused as to what I need to develop on the SF side and what I need to develop on the SQL server side. Please help me understand all the various pieces that I need to create and do. Thank you so much for all your help on this

  2. @Jayesh Tejwani,

    Thanks for wonder full session, I have a question regarding an assignment, that is How to updated verified address on the Event object.
    Should we need to create Trigger on Event Object and pass the address from the “Location” field? or How to call web service for verified address and which event record should be updated?

    I am totally confused that which event record should be updated

    I have completed calling web service and get a response from Rest API, but stuck in “Location Verified” field updated in Event Object.

    Can you please guide me in more detail about this assignment?

    Thanks

  3. Completed Assignment for Day 8.
    I have created below the class and this will call API and get verified Address.

    SmartystreetsAPI.getStreetAddress(‘3301 South Greenfield Rd’,’Gilbert’,’AZ’,’85297′);

  4. Completed Assignment for Day 8!

    I have the same question as above – I am done with calling web service and getting a response, but stuck in “Location Verified” field in Event Object. I could not find a way to add a field on standard Event object.

  5. Hi @Jayesh Tejwani,

    I have developed the code and it is working but I am not sure whether I have done it correctly or not.
    could you please let me know the way.

    public class SmartyStreets {

    public static void validateAdd(){
    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint(‘https://us-street.api.smartystreets.com/street-address?auth-id=05b83875-09e2-43a6-517d-d6c5ce1350fd&auth-token=f07F6GSLw1um4sUVKwfh&candidates=10&match=invalid&street=86%20Frontage%20Road&street2=&city=Belmont&state=MA&zipcode=’);
    request.setMethod(‘GET’);
    HttpResponse response = new HttpResponse();
    response = http.send(request);
    system.debug(‘Response–>’+response.getBody());
    if(response.getStatusCode() == 200){
    system.debug(‘Response–>’+response.getBody());
    List mp = (List)system.JSON.deserializeUntyped(response.getBody());
    system.debug(‘List–>’+mp);
    Map m = (Map)mp[0];
    system.debug(‘List–>’+m.get(‘components’));
    Map mpc = (Map)m.get(‘components’);
    for(string o : mpc.keyset()){
    if(mpc.get(o)==’Hinckley’){
    try{
    Event e = new Event();
    e.Location = ‘Hinckley’;
    e.DurationInMinutes = 20;
    e.ActivityDateTime = system.now();
    insert e;
    system.debug(‘id–>’+e.id);
    }
    catch(Exception e){
    system.debug(‘Message–>’+e.getMessage());
    }
    }
    }
    }
    }
    }

  6. Hello Amit,

    I am tryiing to return the value to visualforce but it is not working if you will help me it will be great.
    visualforce code
    ——————————

    ———————————————–
    apex code
    ——————————

    public class chuckNorris{

    public chuckNorris chuck {get;set;}

    public String type_x {get;set;} //success
    public cls_value value{get;set;}

    public class cls_value {
    public Integer active{get;set;}
    public String confirmed{get;set;}
    public String deaths{get;set;}
    public String deltaconfirmed{get;set;}
    public String deltadeaths{get;set;}
    public String deltarecovered{get;set;}
    public String lastupdatedtime{get;set;}
    public String recovered{get;set;}
    public String state{get;set;}
    public String statecode{get;set;}
    public String statenotes{get;set;} //151
    //public String joke {get;set;} //Chuck Norris doesn’t step on toes. Chuck Norris steps on necks.
    // public cls_categories[] categories {get;set;}
    }

    public class cls_categories {

    }

    public void deserialize () {
    HttpRequest req = new HttpRequest();
    req.setMethod(‘GET’);
    req.setEndpoint(‘https://api.covid19india.org/data.json’);
    Http http = new Http();
    HTTPResponse res = http.send(req);
    String jsonString = res.getBody();

    //Map results = (Map) JSON.deserializeUntyped(jsonString );
    // Cast the values in the ‘animals’ key as a list
    // List statewise = (List) results.get(‘statewise’);
    // System.debug(‘Received the following animals:’);
    chuck = new chuckNorris();
    chuck= (chuckNorris) JSON.deserialize(jsonString,chuckNorris.class);// (chuckNorris)JSON.deserialize(jsonString, chuckNorris.class);

    }

    }

  7. Hello

    I developed this code for Assignment.But When i tried to debug it is showing False,404 Error in Logs.
    Could you please help me to find that what is error in below code or how to outcome from 404 error??

    And I called this class in Anonymous window With Following.

    ApexHourIntigration.verifyAddress(‘[{“candidates”:10,”match”:”invalid”,”street”:”3901 SW 154th Ave”,”street2″:””,”city”:”Davie”,”state”:”FL”,”zipcode”:”33331″}]’);

    ============================================================================
    ============================================================================

    Code
    ==============
    public class ApexHourIntigration {
    public static void verifyAddress(String Address){

    Http Http = new Http();
    HttpRequest Request = new HttpRequest();
    Request.setEndpoint(‘https://us-street.api.smartystreets.com/street-address?auth-id=6baff965-c2ed-eb53-7f43-e615db469a24&auth-token=pq7dRFqRoxtHiXKtCsOt’+ Address);
    Request.setMethod(‘GET’);
    //Request.setHeader(‘contentType’, ‘application-json;charset=UTF-8’);
    //Request.setBody(‘[{“candidates”:10,”match”:”invalid”,”street”:”3901 SW 154th Ave”,”street2″:””,”city”:”Davie”,”state”:”FL”,”zipcode”:”33331″}]’);
    HttpResponse Response = Http.send(Request);

    if(Response.getStatusCode()==200){
    system.debug(Response.getBody());
    }

    if(Response.getStatusCode()==200){
    Map Results = (Map) JSON.deserializeUntyped(Response.getBody());

    List items = (List) Results.get(‘items’);
    for(object item :items){
    Map components = (Map)item;
    system.debug(components.get(‘components’));

    try{
    Event e = new Event();
    e.Location = ‘Verified’;
    update e;
    }
    catch(Exception e){
    system.debug(‘Error is :’+e.getMessage());
    }
    }
    }
    }
    }

    public class ApexHourIntigration {
    public static void verifyAddress(String Address){

    Http Http = new Http();
    HttpRequest Request = new HttpRequest();
    Request.setEndpoint(‘https://us-street.api.smartystreets.com/street-address?auth-id=6baff965-c2ed-eb53-7f43-e615db469a24&auth-token=pq7dRFqRoxtHiXKtCsOt’+ Address);
    Request.setMethod(‘GET’);
    //Request.setHeader(‘contentType’, ‘application-json;charset=UTF-8’);
    //Request.setBody(‘[{“candidates”:10,”match”:”invalid”,”street”:”3901 SW 154th Ave”,”street2″:””,”city”:”Davie”,”state”:”FL”,”zipcode”:”33331″}]’);
    HttpResponse Response = Http.send(Request);

    if(Response.getStatusCode()==200){
    system.debug(Response.getBody());
    }

    if(Response.getStatusCode()==200){
    Map Results = (Map) JSON.deserializeUntyped(Response.getBody());

    List items = (List) Results.get(‘items’);
    for(object item :items){
    Map components = (Map)item;
    system.debug(components.get(‘components’));

    try{
    Event e = new Event();
    e.Location = ‘Verified’;
    update e;
    }
    catch(Exception e){
    system.debug(‘Error is :’+e.getMessage());
    }
    }
    }
    }
    }

  8. Hello,

    Can you please send me a clear explanation of this assignment. I am still confused with how the REST API works

    Thanks in advance

Leave a Reply

Your email address will not be published. Required fields are marked *