๐ŸŒ Real-Time Salesforce to Oracle REST API Integration – Beginner Guide with JSON and Logging

      Salesforce to Oracle REST API Integration

๐Ÿ“˜ Overview

In this blog, we’ll cover a real-time outbound REST API integration from Salesforce to Oracle. When a user clicks a button on a Customer__c record, Salesforce will:

  • Send the customer data + related records (Orders & Addresses) to Oracle

  • Show success or failure messages

  • Log the integration request and response for tracking


๐Ÿ” Use Case

“Send Customer data to Oracle when status = Completed and user clicks Send Data.”

  • If the call is successful: ✅ show a success message

  • If the call fails: ❌ show a failure message

  • In all cases: ๐Ÿงพ store the request and response in a log

 
Visualizing Salesforce-Oracle Integration
Visualizing Salesforce-Oracle Integration

๐Ÿ“ฆ Type of Integration:

 REST API (Outbound)
Salesforce is the client, and Oracle is the server.


๐Ÿงฑ Step-by-Step Implementation:

 Step 1: Get API Details from Oracle Team

Before building anything, ask the Oracle team to share:




Step 2: Create Custom Objects in Salesforce

  1. Customer (Parent)                                  -   Standard Object

  2. Order (Child of Customer)                     - Standard Object

  3. Address__c (Child of Customer)           - Text Fields - Street , City , State, Zip Code, Country and Customer lookup field

  4. Integration_Log__c – to store request/response    - Customer lookup to Customer, Request Body and Response Body is Long Text Area , Status Code is Text field, Timestamp is DataTime field , Success? is checkbox field and Error Message is Long Text Area. 

 

Step 3: Setup Named Credential

Purpose: Store Oracle’s API endpoint securely.

Setup → Named Credentials → New


 

Step 4: Create Apex Class for Integration

This class will:

  • Fetch customer and related records

  • Convert data to JSON

  • Make the callout

  • Handle response

  • Log everything

๐Ÿ”ง Apex Example:

public with sharing class CustomerDataSender {
   
    @AuraEnabled
    public static String sendCustomerToOracle(Id customerId) {
        try {
            // Step 1: Fetch customer
            Customer__c cust = [SELECT Id, Name, Status__c, Email__c FROM Customer__c
WHERE Id = :customerId LIMIT 1];
           
            if (cust.Status__c != 'Completed') {
                return 'Customer status must be Completed.';
            }

            // Step 2: Fetch related Orders
            List<Order__c> orders = [SELECT Id, Order_Date__c, Amount__c FROM Order__c
WHERE Customer__c = :customerId];
           
            // Step 3: Fetch related Addresses
            List<Address__c> addresses = [SELECT Id, City__c, Street__c FROM
Address__c WHERE Customer__c = :customerId];

            // Step 4: Build JSON payload
            Map<String, Object> payload = new Map<String, Object>();
            payload.put('name', cust.Name);
            payload.put('email', cust.Email__c);
           
            // Convert orders to map list
            List<Map<String, Object>> orderList = new List<Map<String, Object>>();
            for (Order__c ord : orders) {
                Map<String, Object> o = new Map<String, Object>();
                o.put('orderDate', String.valueOf(ord.Order_Date__c));
                o.put('amount', ord.Amount__c);
                orderList.add(o);
            }
            payload.put('orders', orderList);

            // Convert addresses to map list
            List<Map<String, Object>> addressList = new List<Map<String, Object>>();
            for (Address__c addr : addresses) {
                Map<String, Object> a = new Map<String, Object>();
                a.put('street', addr.Street__c);
                a.put('city', addr.City__c);
                addressList.add(a);
            }
            payload.put('addresses', addressList);

            // Step 5: Serialize to JSON
            String requestBody = JSON.serialize(payload);

            // Step 6: Prepare callout
            HttpRequest req = new HttpRequest();
            req.setEndpoint('callout:OracleAPI/createCustomer');
            req.setMethod('POST');
            req.setHeader('Content-Type', 'application/json');
            req.setBody(requestBody);

            Http http = new Http();
            HttpResponse res = http.send(req);

            // Step 7: Log integration
            Integration_Log__c log = new Integration_Log__c();
            log.Customer__c = cust.Id;
            log.Request_Body__c = requestBody;
            log.Response_Body__c = res.getBody();
            log.Status_Code__c = String.valueOf(res.getStatusCode());
            insert log;

            // Step 8: Return message
            if (res.getStatusCode() == 200 || res.getStatusCode() == 201) {
                return 'Customer sent successfully!';
            } else {
                return 'Failed to send customer. Response: ' + res.getBody();
            }

        } catch (Exception ex) {
            // Log error
            Integration_Log__c log = new Integration_Log__c();
            log.Customer__c = customerId;
            log.Request_Body__c = 'Error Occurred';
            log.Response_Body__c = ex.getMessage();
            log.Status_Code__c = '500';
            insert log;
            return 'Error: ' + ex.getMessage();
        }
    }
}



Step 5: LWC Button (Optional Frontend Trigger)

You can create a Lightning Web Component with a "Send to Oracle" button to call this Apex method and show toast messages.

1. sendToOracleAction.html

<template>
    <!-- Card wrapper for UI -->
    <lightning-card title="Send Customer Data to Oracle">
        <div class="slds-p-around_medium">
            <!-- Send Button -->
          <!--  <lightning-button
                label="Send to Oracle"
                variant="brand"
                onclick={handleSendClick}>
            </lightning-button>-->

            <!-- Spinner while request is in progress -->
            <template if:true={isLoading}>
                <lightning-spinner alternative-text="Sending..."></lightning-spinner>
            </template>
        </div>
    </lightning-card>
</template>


2. sendToOracleAction.js

import { LightningElement, api } from 'lwc';
import sendCustomerToOracle from '@salesforce/apex/CustomerDataSender.
sendCustomerToOracle';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { CloseActionScreenEvent } from 'lightning/actions';

export default class SendToOracleAction extends LightningElement {
    @api recordId;
    isLoading = true;

    // Automatically send data when component is loaded
    connectedCallback() {
        this.sendData();
    }

    sendData() {
        sendCustomerToOracle({ customerId: this.recordId })
            .then(result => {
                this.showToast('Success', result, 'success');
                this.closeAction();
            })
            .catch(error => {
                this.showToast('Error', error.body.message, 'error');
                this.closeAction();
            });
    }

    showToast(title, message, variant) {
        this.dispatchEvent(new ShowToastEvent({ title, message, variant }));
    }

    closeAction() {
        this.dispatchEvent(new CloseActionScreenEvent());
    }
}


3. sendToOracleAction.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>59.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordAction</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordAction">
            <objects>
                <object>Customer__c</object>
            </objects>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>


Next ๐Ÿชœ Step-by-Step: Add Custom Button as Lightning Action

Go to Object Manager

  1. Go to Setup → Search for Object Manager

  2. Select your object → e.g. Customer

Create Lightning Action

  1. Go to Buttons, Links, and Actions

  2. Click New Action

  3. Set values:

    • Action Type: Lightning Component

    • Lightning Component: c:sendToOracleAction

    • Label: Send to Oracle

    • Name: (auto-filled)

  4. Click Save

Add Action to Page Layout

  1. Still inside the Customer object, go to Page Layouts

  2. Choose your layout (e.g., Customer Layout)

  3. Scroll to Mobile & Lightning Actions

  4. Drag "Send to Oracle" action from top palette into that section

  5. Save the layout


Try it Out!

  1. Go to any Customer__c record

  2. At the top-right, you'll see the Send to Oracle button

  3. Click it:

    • Modal pops up

    • Data is sent to Oracle immediately (via connectedCallback)

    • Success/failure toast is shown

    • Modal closes automatically


Step 6: Test the Integration (End-to-End)

This step ensures your "Send to Oracle" button actually:

  • Sends data to Oracle

  • Shows success or failure

  • Logs the response in Salesforce

๐Ÿชœ 1. Prepare Test Data

  1. Go to App Launcher → search for and open Customer

  2. Create a new Customer or open an existing one

  3. Set Status__c = "Completed" (or your equivalent status field)

    ๐Ÿ“ This should match the logic in your Apex controller that checks status before sending.


๐Ÿชœ 2. Click the "Send to Oracle" Button

  1. Open the Customer__c record

  2. In the top-right action bar, click Send to Oracle

  3. A modal opens

  4. Behind the scenes:

    • LWC sends JSON data to Oracle via REST API

    • Shows success or error toast

    • Modal closes automatically

๐ŸŸข You should see:
Success message (if Oracle returns 200 OK)
Error message (if Oracle failed or is unreachable)

๐Ÿชœ 3. Check Integration Logs in Salesforce

๐Ÿ”ง If you created a custom object like Integration_Log__c:

  1. Go to App Launcher → open Integration Logs tab

  2. Look for the most recent log entry

  3. You’ll see fields like:

    • Customer__c (lookup to the customer)

    • Status__c (Success or Failed)

    • Request_Body__c (sent JSON)

    • Response_Body__c (Oracle’s reply)

    • Timestamp

๐Ÿงช Why this matters?
Helps debugging
Helps support team track history
Auditable in real time

๐Ÿชœ 4. Confirm with Oracle Team (Optional)

If Oracle is a real external system and you're working with their devs:

  1. Share the Customer ID or Order ID

  2. Ask Oracle team:

    • Did they receive the payload?

    • Was it processed correctly?

    • Was there an error?

  3. They might also provide a response like:

 Step 7: JSON Explained

This is how the final JSON might look:

{
  "name": "John Smith",
  "email": "john@example.com",
  "orders": [
    { "orderDate": "2024-04-01", "amount": 100 },
    { "orderDate": "2024-04-02", "amount": 150 }
  ],
  "addresses": [
    { "street": "Main St", "city": "Mumbai" }
  ]
}


๐Ÿ“Œ Summary Table


Thank you for exploring Salesforce to Oracle REST API Integration!

I hope this guide provided valuable insights into real-time outbound API connections.
For a better experience, I recommend viewing this blog on a desktop, as the mobile version is still being optimized.
Your feedback and thoughts mean a lot—please share your comments below.

Happy integrating!

Blog by Yeshwanth










Comments

Popular posts from this blog

The Salesforce Playbook: A Beginner's Guide to Success

Sales/Service/Marketing/Lead Process