Salesforce Integration with External API Example: A Step-by-Step Guide

Integrating Salesforce with external APIs allows organizations to seamlessly connect with third-party systems, enhancing productivity and enabling advanced workflows. In this guide, we’ll explore a practical example of integrating Salesforce with an external REST API using Apex.


What Is Salesforce API Integration?

Salesforce API integration connects Salesforce with external systems for:

  • Data synchronization between platforms.
  • Triggering external services based on Salesforce actions.
  • Automating workflows involving third-party systems.

Integration Use Case

Objective

We’ll create an integration to fetch weather data from a public API (e.g., OpenWeatherMap) and display it on a custom Salesforce record page.


Step-by-Step Implementation

Step 1: Set Up API Access

  1. Register for API Access:
    • Sign up at OpenWeatherMap or another public API provider.
    • Obtain an API key for authentication.
  2. API Endpoint Example:
    • URL: https://api.openweathermap.org/data/2.5/weather?q=CityName&appid=YourAPIKey
    • Replace CityName with a dynamic city name and YourAPIKey with the API key.

Step 2: Create an Apex Class for API Callout

  1. Define the Apex Class:
    • Go to SetupApex ClassesNew.
    • Replace Custom_Object__c and Weather_Temperature__c with your custom object and field names.

Write the Callout Code:

public with sharing class WeatherAPIService {
    @future(callout=true)
    public static void fetchWeatherData(String cityName, Id recordId) {
        try {
            // API endpoint
            String endpoint = 'https://api.openweathermap.org/data/2.5/weather?q=' + cityName + '&appid=YourAPIKey';
            Http http = new Http();
            HttpRequest request = new HttpRequest();
            request.setEndpoint(endpoint);
            request.setMethod('GET');

            // Make the callout
            HttpResponse response = http.send(request);

            if (response.getStatusCode() == 200) {
                // Parse the JSON response
                Map<String, Object> responseBody = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
                Map<String, Object> mainData = (Map<String, Object>) responseBody.get('main');
                Decimal temperature = (Decimal) mainData.get('temp');

                // Update Salesforce record
                Custom_Object__c recordToUpdate = [SELECT Id, Weather_Temperature__c FROM Custom_Object__c WHERE Id = :recordId];
                recordToUpdate.Weather_Temperature__c = temperature;
                update recordToUpdate;
            } else {
                System.debug('Error in API call: ' + response.getStatus());
            }
        } catch (Exception e) {
            System.debug('Exception during API call: ' + e.getMessage());
        }
    }
}

Step 3: Add a Button to Trigger the Integration

  1. Navigate to Object Manager:
    • Go to SetupObject Manager → Select your custom object.
  2. Create a Button:
    • Go to Buttons, Links, and ActionsNew Button or Link.
    • Label: Fetch Weather.
    • Display Type: Detail Page Button.
    • Behavior: Execute JavaScript.
  3. Add the Button to Page Layout:
    • Go to Page Layouts → Drag the button to the layout.

Code:

{!REQUIRESCRIPT("/soap/ajax/48.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/48.0/apex.js")}

sforce.apex.execute("WeatherAPIService", "fetchWeatherData", {
    cityName: "{!Custom_Object__c.City__c}",
    recordId: "{!Custom_Object__c.Id}"
});

alert("Weather data is being fetched.");

Step 4: Test the Integration

  1. Create a Test Record:
    • Add a record in your custom object with a valid city name in the City__c field.
  2. Click the Button:
    • Open the record and click the Fetch Weather button.
  3. Verify the Data:
    • Check the updated Weather_Temperature__c field for the fetched temperature.

Step 5: Handle Security and API Limits

  1. Add Remote Site Settings:
    • Go to SetupRemote Site SettingsNew Remote Site.
    • Add the API domain (e.g., https://api.openweathermap.org).
  2. Consider API Limits:
    • Monitor API limits and configure the integration to handle retries or fallback gracefully.

Best Practices for Salesforce API Integration

  1. Secure API Keys:
    • Store API keys in Salesforce Custom Settings or Custom Metadata for better security.
  2. Handle Errors Gracefully:
    • Use robust error handling and log errors for debugging.
  3. Test in Sandbox:
    • Always test integrations in a Salesforce sandbox environment before deploying to production.
  4. Optimize Callouts:
    • Minimize API callouts by caching responses or using batch processing.

Conclusion

Integrating Salesforce with external APIs enables powerful workflows and data synchronization. This guide demonstrated how to fetch weather data from an external API and update a Salesforce record. By following these steps and best practices, you can build seamless integrations tailored to your business needs, enhancing the value of your Salesforce platform.