Salesforce Integration Crash Course

API is an interface that allows two or more applications to talk to each other. In our Salesforce Integration Crash Course session, we’re going to use postman as a client, if you’re not aware of postman don’t worry. For now you can assume that it’s a client using which we’ll send requests to salesforce server. We will the inbound and outbound Integration in Salesforce using demo.

What is Integration?

Connecting different software applications/systems and enable them to interact with one another exchange data and perform actions. Learn more from our Salesforce Integration post.

Integration Key Terminologies

  • API: Application Programming Interface.
  • Server: A machine where APIs/Services are hosted.
  • Client: A machine running a program which send request(s) to server (call APIs) to perform actions on the server.
Salesforce Integration Crash Course
Salesforce Integration Crash Course

How to connect to salesforce using Postman?

Let see the example of inbound Salesforce integration using postman. In this example we will use Postman as client.

What is Postman?

  • A platform for building and using APIs
  • We can test our standard/custom salesforce REST APIs using postman
  • You can download postman from: https://www.postman.com/downloads/.

Before using the Postman we need to create the connected app in Salesforce.

What is Connected App?

  • A framework that enables an external system to integrate with Salesforce using APIs
  • Helps in performing authentication and authorization and can be used to extract data from salesforce (perform operation) using an access token once permission is granted.

Check our Test Salesforce Rest API using postman for step by step process to create connected app and connect with postman.

OAuth 2.0 Web Server Flow

For demo we will use OAuth 2.0 Web Server Flow.

OAuth 2.0 Web Server Flow
OAuth 2.0 Web Server Flow

Please check below video for end to end step and demo to execute REST API from postman. Learn more about REST API in Salesforce from our post. This post contain all request and URL which you need to execute from postman.

How to create Custom REST API in Salesforce?

Sometimes we need to do some customization in OOB REST API for some complex implementation. Create an apex class with @RestResource annotation and specify a URL mapping. Bind your apex class methods with different types of HTTP Requests using annotations including:

  1. @HTTPGet
  2. @HTTPPost
  3. @HTTPDelete
  4. @HTTPPut
  5. @HTTPPatch

Example of Custom REST API

// Setting up the Request URL
@RestResource(urlMapping='/ContactAPI/*')
global with sharing class ContactResource {

    // Get Method
    @HTTPGet
    global static List<Contact> getContactIdAndNames() {
        // Initializing the request parameter with the incoming request
        RestRequest contactRequest = RestContext.request;
        // Getting the request URI
        String contactRequestURI = contactRequest.requestURI;
        // Getting the limit from the request URI
        Integer contactLimit = Integer.valueOf(contactRequestURI.substring(contactRequestURI.lastIndexOf('/') + 1));
        // Querying contacts
        List<Contact> contactList = [SELECT Id, Name FROM Contact LIMIT :contactLimit];
        // Returning the contacts in the response
        return contactList;
    }

    // POST Method
    @HTTPPost
    global static Contact createNewContact(String firstName, String lastName, String birthDate, String leadSource) {
        // Initializing New Contact
        Contact contact = new Contact();
        contact.FirstName = firstName;
        contact.LastName = lastName;
        contact.Birthdate = Date.parse(birthDate);
        contact.LeadSource = leadSource;
        // Inserting Contact
        insert contact;
        // Returning the contact in the response
        return contact;
    }

    // DELETE Method
    @HTTPDelete
    global static Map<String, String> deleteContact() {
        // Initializing the response map
        Map<String, String> responseMap = new Map<String, String>();
        // Initializing the request parameter with the incoming request
        RestRequest contactRequest = RestContext.request;
        // Getting the request URI
        String contactRequestURI = contactRequest.requestURI;
        // Getting the contact id from the request URI
        Id contactId = Id.valueOf(contactRequestURI.substring(contactRequestURI.lastIndexOf('/') + 1));
        // Initializing contact to delete
        Contact contact = new Contact(Id=contactId);
        // Deleting contact
        try {
            delete contact;
            responseMap.put('success', '1');
            responseMap.put('message', 'Record Deleted Successfully');
        } catch(DmlException ex) {
            responseMap.put('success', '0');
            responseMap.put('message', ex.getMessage());
        }
        // Returning the response map in the response
        return responseMap;
    }

    // PUT Method
    @HTTPPut
    global static Contact upsertContact(String firstName, String lastName, String birthDate, String leadSource) {
        // Initializing the request parameter with the incoming request
        RestRequest contactRequest = RestContext.request;
        // Getting the request URI
        String contactRequestURI = contactRequest.requestURI;
        // Getting the contact id from the request URI
        String contactId = contactRequestURI.substring(contactRequestURI.lastIndexOf('/') + 1);
        // Initializing contact to upsert
        Contact contact = new Contact();
        // Assigning id to the contact if the contact id obtained from the URL is not empty
        if(String.isNotEmpty(contactId)) {
            contact.Id = contactId;
        }
        contact.FirstName = firstName;
        contact.LastName = lastName;
        contact.Birthdate = Date.parse(birthDate);
        contact.LeadSource = leadSource;
        // Upserting Contact
        upsert contact;
        // Returning the contact in the response
        return contact;
    }

    // PATCH Method
    @HTTPPatch
    global static Contact updateContact() {
        // Initializing the request parameter with the incoming request
        RestRequest contactRequest = RestContext.request;
        // Getting the request URI
        String contactRequestURI = contactRequest.requestURI;
        // Getting the contact id from the request URI
        String contactId = contactRequestURI.substring(contactRequestURI.lastIndexOf('/') + 1);
        // Getting the request body from the request
        String requestBody = contactRequest.requestBody.toString();
        // Creating an instance of contact object
        Contact contact;
        // Checking if the contact id obtained from the URL is not empty
        if(String.isNotEmpty(contactId)) {
            // Deserializing the JSON response body and assigning it to the instance of Contact object
            contact = (Contact) JSON.deserialize(requestBody, Contact.class);
            // Assigning the contact id
            contact.Id = contactId;
            // Updating Contact
            update contact;
        }
        // Returning the contact in the response
        return contact;
    }
}

You cannot have multiple methods with same annotation.

How to perform callout from Salesforce?

Add the external site base URL to remote site settings. Perform the callout using the following classes:

  • HTTP
  • HTTPRequest
  • HTTPResponse

Example for perform callout from Salesforce

public with sharing class SFDCStopCallout {
    public static void getBlogs() {
        // Creating an instance of HTTP class
        HTTP http = new HTTP();
        // Creating an instance of HTTPRequest class
        HTTPRequest request = new HTTPRequest();
        // Setting up the endpoint and method for the HTTP request
        request.setEndpoint('https://sfdcstop.herokuapp.com/blogs');
        request.setMethod('GET');
        // Hitting the API and getting the response
        HTTPResponse response = http.send(request);
        // Checking the status code in the response
        if(response.getStatusCode() == 200) {
            // Deserializing the JSON response using the wrapper class
            SFDCStopBlogsWrapper responseWrapper = SFDCStopBlogsWrapper.parse(response.getBody());
            // Displaying the author information
            System.debug('Author:- ' + responseWrapper.author);
            if((responseWrapper.blogs!=null) && (!responseWrapper.blogs.isEmpty())) {
                // Displaying the information of each blog one by one
                for(Integer i=0; i<responseWrapper.blogs.size(); i++) {
                    SFDCStopBlogsWrapper.Blogs blog = responseWrapper.blogs.get(i);
                    System.debug('Blog Id:- ' + blog.id);
                    System.debug('Blog Title:- ' + blog.title);
                    System.debug('Blog URL:- ' + blog.url);
                }
            }
        }
    }
}

Response Wrapper

//
// Generated by JSON2Apex http://json2apex.herokuapp.com/
//
// Wrapper class for SFDC Stop API
public class SFDCStopBlogsWrapper {
	public class Blogs {
		public String id;
		public String title;
		public String url;
	}
	public String author;
	public List<Blogs> blogs;
	public static SFDCStopBlogsWrapper parse(String json) {
		return (SFDCStopBlogsWrapper) System.JSON.deserialize(json, SFDCStopBlogsWrapper.class);
	}
}

New to wrapper class? Check out our Wrapper Class in Salesforce post.

Salesforce Integration Crash Course Video

YouTube video

Resources for further learning

Amit Chaudhary
Amit Chaudhary

Amit Chaudhary is Salesforce Application & System Architect and working on Salesforce Platform since 2010. He is Salesforce MVP since 2017 and have 17 Salesforce Certificates.

He is a active blogger and founder of Apex Hours.

Articles: 461

Leave a Reply

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