All Salesforce API’s, How, When & What to use

All Salesforce API's How, When & What to use Salesforce Shastras

Salesforce APIs play a crucial role in enabling external applications to communicate with Salesforce data, leveraging its features to create rich, custom experiences and streamline business processes. With a variety of APIs available, it’s essential to understand which is right for your use case. This post will guide you through the All Salesforce API’s, providing real-time examples to help you make an informed decision.

Understanding Different Types of Salesforce APIs

REST API

Type: REST 

Data Format: JSON, XML 

Communication: Synchronous 

Example: Integrating Salesforce with a custom web application to display customer data in real-time.

When to use:

Getting Information About Your Organization:

  • To retrieve summary information about available API versions, make a GET request to the following endpoint: /services/data/.
  • This will provide you with a list of supported API versions along with their details.
  • Example response:
{
  "versions": [
    {
      "label": "Winter '23",
      "url": "/services/data/v54.0",
      "version": "54.0"
    },
    // Other versions...
  ]
}

To obtain details about Salesforce objects (standard or custom), you can query the sobjects resource. For example:

  • Endpoint: /services/data/v54.0/sobjects/
  • Example response:
{
  "sobjects": [
    {
      "name": "Account",
      "label": "Account",
      "custom": false,
      "keyPrefix": "001",
      // Other fields...
    },
    // Other objects...
  ]
}

Working with Object Metadata:

  • Retrieve object metadata information using the describe resource.
  • Example: To retrieve metadata for the Account object, make a GET request to /services/data/v54.0/sobjects/Account/describe.
  • This will provide details such as field names, data types, picklist values, and relationships.

Working with Records:

  • Create (POST): To create a new record, send a POST request with record data (in JSON or XML format) to the appropriate object endpoint (e.g., /services/data/v54.0/sobjects/Account).
  • Read (GET): Retrieve records by querying objects using SOQL or SOSL.
    • Example: To fetch details of a specific Contact, make a GET request to /services/data/v54.0/query?q=SELECT+Id,Name,Email+FROM+Contact+WHERE+Id='003XXXXXXXXXXXX'.
  • Update (PATCH or PUT): Modify existing records by sending a PATCH or PUT request with updated data.
  • Delete (DELETE): Remove records by making a DELETE request to the record’s endpoint (e.g., /services/data/v54.0/sobjects/Account/001XXXXXXXXXXXX).

Delete Lightning Experience Event Series:

  • Use the HTTP DELETE method to remove events in a series (IsRecurrence2 events).
  • Specify the event ID in the request URL (e.g., /services/data/v54.0/sobjects/Event/00UXXXXXXXXXXXX).

Get an Image from a Rich Text Area Field:

  • Retrieve an image from a custom rich text field (e.g., LeadPhotoRichText__c) using the sObject Rich Text Image Get resource.
  • Example: To retrieve the image associated with a specific record, make a GET request to /services/data/v54.0/sobjects/Custom_Object__c/Record_Id/LeadPhotoRichText__c.

Insert or Update Blob Data:

  • Use sObject resources to insert or update binary large objects (blobs) in Salesforce (e.g., images or PDFs).
  • Upload files or binary data to standard objects with blob fields (e.g., ContentVersion).

Get Blob Data:

  • Retrieve blob data for a given record using the sObject Blob Get resource.
  • Example: To retrieve the blob data for an attachment, make a GET request to /services/data/v54.0/sobjects/Attachment/Attachment_Id/Body.

Working with Recently Viewed Information:

  • Programmatically retrieve and update recently viewed record information.
  • Use REST API Query and Recently Viewed resources.
  • Example: To retrieve recently viewed records, make a GET request to /services/data/v54.0/recent.

Managing User Passwords:

  • Set or reset user passwords using REST API resources.
  • Example: To reset a user’s password, make a POST request to /services/data/v54.0/sobjects/User/UserId/password.

Working with Approval Processes and Process Rules:

  • Use REST API resources to interact with approval processes and process rules.
  • Example: To submit a record for approval, make a POST request to /services/data/v54.0/process/approvals.

Using Event Monitoring:

  • Access event monitoring data through REST API.
  • Useful for assessing org usage trends and user behavior.
  • Example: To retrieve login history events, make a GET request to /services/data/v54.0/query?q=SELECT+Id,EventType,EventDate+FROM+LoginEvent.

SOAP API

Type: SOAP (WSDL) 

Data Format: XML 

Communication: Synchronous 

Example:

Integration with ERP and Finance Systems:

  • Use Case: Your organization wants to seamlessly integrate Salesforce with existing ERP (Enterprise Resource Planning) and finance systems.
  • How SOAP API Helps: SOAP API enables real-time data synchronization between Salesforce and these systems. You can retrieve customer information, update orders, and maintain consistency across platforms.

Real-Time Information Delivery:

  • Use Case: Your company needs to deliver real-time sales and support information to external portals, websites, or other systems.
  • How SOAP API Helps: By using SOAP API, you can push relevant data (such as lead status, case updates, or account details) to external systems, ensuring timely and accurate information for stakeholders.

Customization and Extension:

  • Use Case: You want to extend Salesforce functionality beyond standard features to meet specific business requirements.
  • How SOAP API Helps: SOAP API allows you to create custom solutions tailored to your organization’s needs. For example, you can automate complex workflows, integrate with third-party tools, or build custom interfaces.

Creating and Managing Marketing Content:

  • Use Case: Your marketing team wants to create and manage email templates, campaigns, or personalized content within Salesforce.
  • How SOAP API Helps: You can use SOAP API to programmatically create and update marketing assets. For instance, you can create email templates, associate them with campaigns, and track engagement metrics.

Data Migration and Bulk Operations:

  • Use Case: Your company is migrating data from an old system to Salesforce, or you need to perform bulk updates (e.g., mass lead conversion).
  • How SOAP API Helps: SOAP API supports batch processing, allowing you to insert, update, or delete records in bulk. You can efficiently migrate historical data or perform periodic data maintenance.

Here’s a simple example of how to create a custom SOAP-based API endpoint in Apex. In this example, we’ll create a method that returns an Account record using a custom SOAP web service:

global with sharing class MySOAPWebService {
    webservice static Account getRecord(String accountId) {
        // Add your code here to retrieve the Account record based on the provided ID
        // For demonstration purposes, let's assume we query the Account by its ID

        // Query the Account
        List<Account> accounts = [SELECT Id, Name, Industry FROM Account WHERE Id = :accountId LIMIT 1];

        if (!accounts.isEmpty()) {
            return accounts[0]; // Return the first Account (or null if not found)
        } else {
            return null; // Account not found
        }
    }
}

Explanation:

  • We define a global class called MySOAPWebService.
  • The webservice keyword indicates that the method can be invoked via SOAP.
  • The getRecord method accepts an accountId as input and returns an Account object.
  • Inside the method, you can customize the logic to retrieve the desired Account record (e.g., querying by ID).
  • In a real-world scenario, you would replace the placeholder logic with actual queries or business logic.

Connect REST API

Type: REST 

Data Format: JSON, XML 

Communication: Synchronous (photos processed asynchronously)

Example: Developing a mobile app that allows users to upload photos which are then attached to their Salesforce records.

  1. Sync Clients Between CRM and ERP Systems:
    • Use Case: As soon as a sales rep closes an opportunity, finance needs to be notified for invoicing. The sync should work bidirectionally.
    • Solution:
      • Integrate your CRM (e.g., Salesforce) with your ERP system (e.g., NetSuite).
      • Build a data flow where closed opportunities in your CRM are added to your ERP system.
      • Bidirectionally sync issues flagged by finance (e.g., invoicing) to notify the designated sales rep.
  2. Send Prospects or Clients Company Swag After Event Registration:
    • Use Case: To make event registrants feel valued, automatically send them company swag.
    • Solution:
      • Integrate your event management platform (e.g., Eventbrite) with your gift-giving platform (e.g., Sendoso).
      • Workflow:
        1. When someone registers for an event, an alert is sent to the gift-giving platform.
        2. The gift-giving platform automatically delivers a predetermined gift to the registrant.
  3. Automatically Provision and Deprovision Users in Your Product:
    • Use Case: When users sign up for your product, they need access to specific features or resources.
    • Solution:
      • Integrate your user management system (e.g., custom-built or third-party) with your product.
      • Workflow:
        1. Upon user registration, trigger an API call to provision necessary resources (e.g., database access, permissions).
        2. When a user account is deactivated, deprovision resources to maintain security.
  4. Add Critical Client Data to Fuel AI and ML Features:
    • Use Case: Enhance your product’s machine learning capabilities by incorporating external data.
    • Solution:
      • Integrate with external systems (e.g., industry-specific databases, third-party APIs).
      • Retrieve relevant data (e.g., market trends, customer behavior) and feed it into your AI/ML models.




Apex REST API

Apex REST API allows you to expose your Apex classes and methods as RESTful web services. By defining your Apex class with the @RestResource annotation, you can make it accessible via REST endpoints. This enables external applications to interact with your Salesforce code and data using standard HTTP methods.

Here are some key points about Apex REST API:

  • Purpose: To provide a way for external systems to communicate with Salesforce using RESTful architecture.
  • Supported Resources: You can expose custom Apex classes and methods as REST resources.
  • Authentication: Supports OAuth 2.0 and session ID-based authentication.
  • Governor Limits: Calls to Apex REST classes count against your organization’s API governor limits.

Type: REST 

Data Format: JSON, XML, Custom 

Communication: Synchronous 

Use Cases for Apex REST API:

  1. Custom Integrations:
    • Scenario: You need to integrate Salesforce with an external system (e.g., a custom-built application, third-party service).
    • Solution: Expose relevant Apex methods via REST endpoints to allow seamless data exchange.
  2. Mobile App Backend:
    • Scenario: You’re building a mobile app that interacts with Salesforce data.
    • Solution: Implement RESTful endpoints in Apex to handle requests from the mobile app (e.g., retrieving records, updating data).
  3. Custom Webhooks:
    • Scenario: You want to receive real-time notifications from external services (e.g., GitHub, payment gateways).
    • Solution: Create REST endpoints in Salesforce to handle incoming webhook notifications.
  4. Data Import and Export:
    • Scenario: You need to import or export data between Salesforce and other systems.
    • Solution: Use Apex REST API to expose data manipulation methods (e.g., insert, update, delete) via REST endpoints.

Example: Basic Apex REST Code Sample

Let’s look at a simple example. Suppose you want to create a REST API to manage custom objects called “Events.” Here’s a basic implementation:

@RestResource(urlMapping='/events/*')
global with sharing class EventRestController {
    @HttpGet
    global static Event__c doGet() {
        RestRequest req = RestContext.request;
        String eventId = req.requestURI.substring(req.requestURI.lastIndexOf('/') + 1);
        // Retrieve the Event record based on eventId (query database or other logic)
        Event__c event = [SELECT Id, Name, Date__c FROM Event__c WHERE Id = :eventId LIMIT 1];
        return event;
    }

    @HttpDelete
    global static void doDelete() {
        RestRequest req = RestContext.request;
        String eventId = req.requestURI.substring(req.requestURI.lastIndexOf('/') + 1);
        // Delete the Event record based on eventId (perform deletion logic)
        // ...
    }
}

In this example:

  • The doGet method retrieves an Event record based on the provided ID.
  • The doDelete method deletes an Event record based on the ID.

Remember to handle authentication, error handling, and any additional business logic specific to your use case.


Apex SOAP API

Apex SOAP API is a powerful tool in the Salesforce ecosystem that allows you to interact with Salesforce data and metadata using the Simple Object Access Protocol (SOAP). Let’s dive into the details

Type: SOAP (WSDL) 

Data Format: XML 

Communication: Synchronous 

Example: Allowing an external billing system to create invoices directly in Salesforce using custom Apex web services.

  • Apex SOAP API enables you to create, retrieve, update, or delete records in Salesforce using SOAP-based web services.
  • It provides a programmatic way to perform CRUD (Create, Read, Update, Delete) operations on Salesforce objects.
  • You can use it to integrate Salesforce with external systems, automate processes, and build custom solutions.
  1. Use Cases of Apex SOAP API:
    • Data Integration: Connect Salesforce with other applications, databases, or services. For example:
      • Syncing data between Salesforce and an external database.
      • Integrating Salesforce with an ERP system.
    • Custom Integrations: Create custom SOAP-based web services in Apex to expose specific functionality to external systems. For instance:
      • Expose an Apex class method as a custom SOAP web service.
      • Allow external applications to invoke this web service to perform actions in Salesforce.
    • Legacy Systems: If you’re working with legacy systems that rely on SOAP, Apex SOAP API bridges the gap.
    • Complex Business Logic: Implement complex business rules or calculations using Apex classes and expose them via SOAP.
    • Testing and Deployment: Use Apex SOAP API calls to deploy your Apex code. Some relevant methods include:
      • compileAndTest(): Compiles and tests Apex classes.
      • compileClasses(): Compiles specified Apex classes.
      • compileTriggers(): Compiles specified triggers.
      • executeanonymous(): Executes anonymous Apex code.
      • runTests(): Runs specified tests.

Sample Code:

  • Let’s create a simple example where we expose an Apex class method as a custom SOAP web service. Imagine we want to retrieve an Account record based on its ID:
global with sharing class MySOAPWebService {
    webservice static Account getRecord(String accountId) {
        // Query the Account based on the provided ID
        return [SELECT Id, Name, Industry FROM Account WHERE Id = :accountId LIMIT 1];
    }
}

Analytics REST API

The Analytics REST API allows you to programmatically interact with CRM Analytics features such as datasets, dashboards, and lenses.

Type: REST 

Data Format: JSON, XML 

Communication: Synchronous 

Example: Fetching analytical data from Salesforce to be displayed on a third-party BI tool.

  1. Querying Data:
    • You can send queries directly to the CRM Analytics Platform using the REST API.
    • Access datasets that have been imported into the platform.
  2. Working with Lenses and Templates:
    • Create and retrieve CRM Analytics lenses.
    • Validate and update templates for CRM Analytics apps.
  3. Managing Assets:
    • Back up and restore previous versions of CRM Analytics dashboards, lenses, and dataflows.
    • Run, schedule, and sync CRM Analytics dataflows, recipes, and connections.
    • Retrieve a list of dataflow job nodes and details for each individual node.
    • Access XMD (Extended Metadata) information.
  4. Creating and Managing Apps:
    • Create and retrieve CRM Analytics apps.
    • Create, update, and retrieve CRM Analytics dashboards.
    • Retrieve a list of dependencies for an application.
  5. Additional Features:
    • Determine what features are available to the user.
    • Work with and schedule Trend in CRM Analytics report snapshots.
    • Manipulate synced datasets (connected objects).
    • Retrieve or update recipe metadata.
    • Get, add, update, and delete ‘eclair’ geo map charts.
  6. Download and Integration:
    • Download a CRM Analytics dashboard or lens as an image or PDF.
    • Get Einstein Discovery predictions on Salesforce objects via the smartdatadiscovery API.

User Interface API

The Salesforce User Interface (UI) API serves as a powerful tool for building custom user interfaces that seamlessly integrate with the Salesforce platform. Whether you’re developing native mobile apps or web applications, the UI API empowers you to create engaging interfaces that users will love.

  • The UI API acts as a bridge between developers and Salesforce, allowing you to build custom UI components.
  • It’s the same API that Salesforce uses to construct Lightning ExperienceSalesforce for AndroidSalesforce for iOS, and mobile web interfaces.
  • With the UI API, you can work with records, list views, actions, favorites, and more.

Type: REST 

Data Format: JSON 

Communication: Synchronous 

Example: Building a custom UI for Salesforce data on an external portal or application.

  • Dynamic Responses: When you request data using the UI API, you receive a single response containing both data and metadata. This response automatically reflects any changes made by Salesforce admins (such as layout modifications, picklist updates, field-level security, and sharing settings).
  • Record Display: To display a specific record, you can make a simple request like this:GET /ui-api/record-ui/001R0000003GeJ1IAK Behind the scenes, Salesforce handles security checks, SOQL queries, object metadata retrieval, theme information, and layout details. The result is a convenient JSON response with all the necessary data and metadata for displaying the record.
  • Building UI Components: Beyond records, you can use the UI API to create UI components for Salesforce actions, favorites, and list views.

GraphQL API

  • As of Winter ’23, the Salesforce GraphQL API is generally available.
  • It provides a new way to create rich, performant mobile and web applications by leveraging the GraphQL query language.
  • Unlike traditional REST APIs, GraphQL allows clients to request exactly the data they need, making it more efficient and flexible.

Type: GraphQL 

Data Format: JSON 

Communication: Synchronous 

Key Features and Benefits:

  • Aggregate Records: Query multiple records and related data in a single request.
  • Explicit Fields: Specify the exact fields you want to retrieve, reducing unnecessary data transfer.
  • Version at Field-Level: Access historical data by querying specific versions of fields.
  • Dynamic Responses: The response automatically reflects changes made by administrators (layouts, field-level security, etc.).
  • Single Endpoint: All data retrieval happens through a single endpoint.
  • Developer-Friendly: Organize queries based on types and fields, not endpoints.
  • Sample Apps: Salesforce provides sample apps demonstrating how to use the GraphQL API.

Example: Creating a flexible data query interface that allows clients to request exactly what they need from Salesforce.

  1. Real-Time Dashboards:
    • Utilizing GraphQL to create real-time dashboard applications can offer a solution for keeping up with constantly evolving data sets.
    • Implementing GraphQL also facilitates the integration of multiple data sources into one streamlined view, facilitating better overall analysis.
  2. Social Media Analytics:
    • With GraphQL, you can directly access materialized views in the database through the defined schema, abstracting away the complexities of the underlying database structure.
    • A social media analytics platform can leverage GraphQL to offer a flexible API for querying and analyzing user-generated content.
  3. Subscriptions and Live Queries:
    • Subscriptions are the go-to solution for adding real-time capabilities to a GraphQL-powered application.
    • GraphQL Live Queries, often used in the context of subscriptions, allow clients to receive real-time updates as data changes.

Remember, GraphQL’s flexibility and ability to fetch precisely the data needed make it an excellent choice for scenarios where real-time interactions and dynamic data are crucial!


Tooling API

  • The Tooling API allows you to build custom development tools or apps for Lightning Platform applications.
  • It provides fine-grained access to an org’s metadata, making it ideal for creating interactive applications.
  • You can use both SOAP and REST interfaces to interact with the Tooling API.

Type: REST or SOAP (WSDL) 

Data Format: JSON, XML, Custom 

Communication: Synchronous 

Example: Automating the setup of development environments by scripting the creation of custom objects and fields in Salesforce.

  • Custom Development Tools: Build specialized tools for specific applications or services.
  • Integration with Enterprise Tools: Incorporate dynamic modules for Lightning Platform development into your existing enterprise integration tools.
  • Enhance Existing Tools: Add features and functionality to your current Lightning Platform tools.

Sample Requests (using REST):

  • To get a description of all available objects in Tooling API:
    • GET /services/data/v60.0/tooling/sobjects/
  • To get a description of a specific Tooling API object (e.g., TraceFlag):
    • GET /services/data/v60.0/tooling/sobjects/TraceFlag/
  • To create a new Tooling API object (e.g., MetadataContainer):
    • POST /services/data/v60.0/tooling/sobjects/MetadataContainer/ Body: {"Name": "TestContainer"}
  • To retrieve a Tooling API object by ID (e.g., MetadataContainer):
    • GET /services/data/v60.0/tooling/sobjects/MetadataContainer/{containerID}/
  • To update a Tooling API object by ID (e.g., MetadataContainer):
    • PATCH /services/data/v60.0/tooling/sobjects/MetadataContainer/{containerID}/ Body: {"Name": "NewlyNamedContainer"}
  • To query a Tooling API object by ID (e.g., MetadataContainer):
    • GET /services/data/v60.0/tooling/query/?q=Select+id,Name+from+MetadataContainer+Where+ID='{containerID}'

Explore Metadata:

  • Use Tooling API to retrieve metadata information, manipulate objects, and query within metadata containers.
  • For detailed descriptions of Tooling API objects and their REST resources and SOAP calls, refer to the Tooling API Objects documentation.

Bulk API 2.0

  • Bulk API 2.0 is a RESTful API designed for performing large-scale data operations on Salesforce objects.
  • It allows you to asynchronously insert, update, delete, and query large datasets within your Salesforce org.
  • Unlike synchronous APIs, Bulk API 2.0 processes requests in the background, making it ideal for handling substantial data volumes.

Type: REST 

Data Format: CSV 

Communication: Asynchronous 

Example: Performing large data migrations or integrations where thousands of records need to be inserted or updated in Salesforce.

  • Data Ingestion:
    • Use Bulk API 2.0 to insert, update, upsert, or delete large sets of records.
    • Prepare your data in a comma-separated value (CSV) file format and create a job to upload it.
  • Bulk Queries:
    • Perform asynchronous SOQL queries that return large amounts of data (10,000 records or more).
  • Consistent Design:
    • Bulk API 2.0 provides a streamlined and consistent interface for loading data into your Salesforce org.
    • It is well-integrated with other Salesforce APIs.
  • Future-Proof:
    • Bulk API 2.0 is designed for future innovation and enhancements.

Metadata API

  • The Metadata API allows you to build custom development tools or apps for Lightning Platform applications.
  • It provides fine-grained access to an org’s metadata, making it ideal for creating interactive applications.
  • You can use both SOAP and REST interfaces to interact with the Metadata API.
  • Metadata describes other data in your Salesforce org.
  • While business data includes records directly related to your company’s operations (such as addresses, accounts, or products), Salesforce metadata defines the schema, process, presentation, authorization, and general configuration of your org.
  • For example, schema metadata describes the properties of business data. Address fields like “Address Type,” “City,” and “Postal Code” are schema metadata, while the corresponding values (e.g., “Mailing address,” “Chicago, IL,” and “60106”) are actual data.
  • Metadata also defines how your org functions, including process behavior, presentation layout, and user authorization.

Type: SOAP (WSDL) 

Data Format: XML 

Communication: Asynchronous 

Example: Deploying changes from a sandbox environment to production or retrieving metadata for version control.

  • Use Metadata API to:
    • Retrieve, deploy, create, update, or delete customization information (e.g., custom object definitions, page layouts).
    • Develop customizations and build tools that manage the metadata model (not the data itself).
    • Move metadata between Salesforce orgs during the development process.
  • Note that Metadata API doesn’t directly work with business data (e.g., accounts, leads); for those operations, use SOAP API or REST API.
  • Deploy and retrieve metadata using:
    • deploy() and retrieve() calls: Useful for moving the full metadata model during final stages of development (e.g., deploying tested customizations to production).
    • Source push and pull commands: Efficient for moving only changes in metadata.

Pub/Sub API

  • The Pub/Sub API enables you to subscribe to real-time event streams and integrate external systems with real-time events.
  • Event streams are based on custom payloads through platform events or changes in Salesforce records through Change Data Capture.

Type: gRPC and protocol buffers 

Data Format: Binary 

Communication: Asynchronous 

Example: Implementing event-driven architecture by subscribing to real-time events from Salesforce and triggering workflows in external systems

  • Real-Time Event Streams:
    • Subscribe to events as they occur, allowing you to react promptly to changes in your Salesforce org.
    • Receive notifications about custom events or record updates.
  • Custom Payloads:
    • Define custom payloads for platform events, tailoring the data you receive.
    • Platform events represent significant business occurrences and can trigger actions in external systems.
  • Change Data Capture (CDC):
    • Capture changes in Salesforce records (inserts, updates, deletes) and propagate them to external systems.
    • CDC events provide granular information about data modifications.
  • Integration Flexibility:

Leave a Reply

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