Transfer REST API Request Between Salesforce Orgs?

Transfer REST API Request Between Salesforce Orgs?

On March 12, 2025, Posted by , In Salesforce Apex Tutorial, With Comments Off on Transfer REST API Request Between Salesforce Orgs?
Transfer REST API Request Between Salesforce Orgs

Question:

We have two Salesforce orgs: Org1 and Org2. Currently, Org1 receives an inbound API request from an external system. The request is a Salesforce standard composite API call that posts platform event content in the request body. A trigger in Org1 listens to the event and processes the business workflow.

For operational reasons, we need to transfer the API request from Org1 to Org2. The idea is that once Org1 receives the API request, it should redirect the request to Org2. Org2 will then process the request using its own trigger to complete the workflow.

Without using licensed tools like Mulesoft Anypoint or other connectors, what are the possible ways to achieve this? The two approaches I have considered so far are:

Authenticating Org2 from Org1 using OAuth and sending an HTTP POST request to publish the event. The trigger in Org2 would process the event.

Exposing a custom REST resource in Org2, where Org1 authenticates and invokes the REST endpoint, passing the payload as a parameter. The REST resource in Org2 then constructs and publishes the platform event.

    Are there any additional approaches for transferring the request between the two orgs?

    Accelerate your Salesforce career with expert-led Salesforce training in Hyderabad, featuring hands-on projects and guidance for beginners and professionals.

    Answer:

    Here are the possible approaches to transfer the API request from Org1 to Org2 without using licensed tools:

    1. Use OAuth and HTTP POST

    Org1 can authenticate itself with Org2 using an OAuth 2.0 flow and then construct an HTTP POST request to publish the platform event in Org2. Below is an example:

    Step 1: Authenticate Org1 with Org2 using OAuth.

    HttpRequest req = new HttpRequest();
    req.setEndpoint('https://login.salesforce.com/services/oauth2/token');
    req.setMethod('POST');
    req.setBody('grant_type=password&client_id=CLIENT_ID&client_secret=CLIENT_SECRET&username=ORG2_USERNAME&password=ORG2_PASSWORD');
    
    // Send the request and parse the response for the access token
    Http http = new Http();
    HttpResponse res = http.send(req);
    Map<String, Object> tokenResponse = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
    String accessToken = (String) tokenResponse.get('access_token');

    Code Explanation : The first snippet authenticates Org1 with Org2 by sending a POST request to Salesforce’s OAuth token endpoint. It uses the client ID, client secret, username, and password to retrieve an access token, which is then used for authorized API calls.

    Step 2: Construct and send the HTTP POST request to Org2’s platform event endpoint.

    HttpRequest postRequest = new HttpRequest();
    postRequest.setEndpoint('https://ORG2_INSTANCE.my.salesforce.com/services/data/v57.0/sobjects/PlatformEvent__e');
    postRequest.setMethod('POST');
    postRequest.setHeader('Authorization', 'Bearer ' + accessToken);
    postRequest.setHeader('Content-Type', 'application/json');
    postRequest.setBody('{ "Field1__c": "Value1", "Field2__c": "Value2" }');
    
    Http postHttp = new Http();
    HttpResponse postResponse = postHttp.send(postRequest);
    System.debug(postResponse.getBody());

    Code Explanation : The second snippet constructs an HTTP POST request to Org2’s /sobjects/PlatformEvent__e endpoint, using the access token for authentication. It sends a JSON payload that contains the platform event data to be published in Org2.

    2. Expose a Custom REST Resource in Org2

    You can create a custom REST endpoint in Org2 that receives the request from Org1 and publishes the platform event. Here’s how:

    Step 1: Define the REST resource in Org2.

    @RestResource(urlMapping='/PublishEvent')
    global with sharing class EventPublisher {
        @HttpPost
        global static void publishEvent() {
            RestRequest req = RestContext.request;
            String payload = req.requestBody.toString();
            Map<String, Object> data = (Map<String, Object>) JSON.deserializeUntyped(payload);
    
            // Publish the platform event
            PlatformEvent__e event = new PlatformEvent__e(Field1__c = (String) data.get('Field1'), Field2__c = (String) data.get('Field2'));
            EventBus.publish(event);
        }
    }

    Code Explanation : The third snippet defines a custom REST API endpoint in Org2. It listens for POST requests, deserializes the incoming JSON payload into a Map, constructs a platform event using the received data, and publishes it.

    Step 2: Authenticate Org1 with Org2 and invoke the REST resource.

    HttpRequest req = new HttpRequest();
    req.setEndpoint('https://ORG2_INSTANCE.my.salesforce.com/services/apexrest/PublishEvent');
    req.setMethod('POST');
    req.setHeader('Authorization', 'Bearer ' + accessToken);
    req.setHeader('Content-Type', 'application/json');
    req.setBody('{ "Field1": "Value1", "Field2": "Value2" }');
    
    Http http = new Http();
    HttpResponse res = http.send(req);
    System.debug(res.getBody());

    Code Explanation : The fourth snippet demonstrates Org1 invoking Org2’s custom REST endpoint. It sends the platform event data in the request body, authenticates using the OAuth token, and ensures secure communication with proper headers.

    3. Use a Message Queue or Middleware (Optional, No Licenses)

    If you prefer not to rely on direct API calls, you could set up an intermediary system (e.g., a message queue like AWS SQS or an open-source message broker) to handle the communication. Org1 can post messages to the queue, and Org2 can poll or subscribe to the queue to retrieve and process them.

    Summing up

    To transfer inbound REST API requests between Salesforce orgs without licensed tools, you can leverage OAuth authentication and HTTP POST requests or create a custom REST API in the target org. Using OAuth, Org1 authenticates with Org2 and directly posts platform event data via the standard endpoint, enabling the trigger in Org2 to process it. Alternatively, exposing a custom REST resource in Org2 allows Org1 to forward the payload, where the REST API constructs and publishes the event. Both methods ensure secure, scalable communication without external middleware, while an optional message queue can decouple the integration further if needed.

    Kickstart Your Salesforce Career with Training in Hyderabad

    Ready to boost your career with Salesforce? CRS Info Solutions offers top-tier Salesforce training in Hyderabad, designed to provide you with the skills needed to excel in the dynamic Salesforce ecosystem. Our expert-led courses cover critical modules like Salesforce Admin, Developer, and AI, with an emphasis on real-time project experience to ensure you gain hands-on expertise. Whether you’re a beginner or an experienced professional, our training prepares you for the challenges of the Salesforce world.

    Our Salesforce training in Hyderabad focuses on practical, industry-relevant learning. With personalized guidance, comprehensive course materials, and expert support for certification and interview prep, we make sure you’re job-ready.

    Enroll today for a free demo session and take the first step towards a successful Salesforce career!!!

    Comments are closed.