SalesforceにおけるWebサービスコールアウトのテスト完全ガイド

Aura と LWC での REST API 統合: コード例とセキュリティ考慮事項


Salesforce REST URL を Lightning Component から呼び出す方法

Lightning Component (Aura または LWC) では、Salesforce REST API を利用してデータを取得または操作することができます。以下は、Salesforce REST URL を Lightning Component から呼び出す際の詳細な手順とサンプルコードを紹介します。


手順

1. Apex コントローラーを作成する

Lightning Component から REST API を呼び出すには、Apex コントローラーを経由するのが推奨されます。HttpRequest クラスを使用して REST URL を呼び出します。

Apex コントローラー例:

public with sharing class RESTApiController {
    @AuraEnabled
    public static String callRestApi(String endpoint) {
        try {
            Http http = new Http();
            HttpRequest request = new HttpRequest();
            request.setEndpoint(endpoint);
            request.setMethod('GET');
            request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());

            HttpResponse response = http.send(request);
            if (response.getStatusCode() == 200) {
                return response.getBody();
            } else {
                throw new CalloutException('Failed to call REST API. Status Code: ' + response.getStatusCode());
            }
        } catch (Exception e) {
            throw new AuraHandledException('Error occurred: ' + e.getMessage());
        }
    }
}

ポイント:

  • Authorization ヘッダーに Bearer トークンを使用して、Salesforce API 認証を処理。
  • @AuraEnabled アノテーションで Lightning Component から呼び出せるように設定。

2. Lightning Component を作成する (Aura Components の場合)

Apex コントローラーを呼び出し、結果を表示するための Aura コンポーネントを作成します。

コンポーネント (HTML):

<aura:component controller="RESTApiController" implements="flexipage:availableForAllPageTypes">
    <aura:attribute name="endpoint" type="String" default="/services/data/v57.0/sobjects/Account" />
    <aura:attribute name="response" type="String" />

    <lightning:button label="Call REST API" onclick="{!c.callApi}" />
    <lightning:textarea value="{!v.response}" label="API Response" readonly="true" />
</aura:component>

コンポーネントコントローラー (JS):

({
    callApi: function (component, event, helper) {
        let endpoint = component.get("v.endpoint");
        let action = component.get("c.callRestApi");
        action.setParams({ endpoint: endpoint });

        action.setCallback(this, function (response) {
            let state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.response", response.getReturnValue());
            } else {
                let errors = response.getError();
                let message = errors && errors[0] ? errors[0].message : "Unknown error";
                component.set("v.response", "Error: " + message);
            }
        });

        $A.enqueueAction(action);
    }
});

3. Lightning Web Component (LWC) の場合

LWC でも同様のプロセスで実装できます。

HTML ファイル:

<template>
    <lightning-input label="Endpoint" value={endpoint} onchange={handleEndpointChange}></lightning-input>
    <lightning-button label="Call REST API" onclick={callApi}></lightning-button>
    <lightning-textarea label="API Response" value={response} readonly></lightning-textarea>
</template>

JS ファイル:

import { LightningElement, track } from 'lwc';
import callRestApi from '@salesforce/apex/RESTApiController.callRestApi';

export default class RestApiCall extends LightningElement {
    @track endpoint = '/services/data/v57.0/sobjects/Account';
    @track response = '';

    handleEndpointChange(event) {
        this.endpoint = event.target.value;
    }

    callApi() {
        callRestApi({ endpoint: this.endpoint })
            .then((result) => {
                this.response = result;
            })
            .catch((error) => {
                this.response = 'Error: ' + error.body.message;
            });
    }
}

セキュリティの考慮事項

  1. Apex コールアウトを使用する理由:

    • REST API を直接 JavaScript から呼び出すと、CORS の問題やセキュリティリスクが発生します。
    • Apex 経由で呼び出すことで、Salesforce ドメイン内での安全な通信が可能です。
  2. API バージョンの互換性:

    • エンドポイントに指定するバージョン (v57.0 など) は、組織の設定に応じて調整してください。
  3. 認証:

    • この例では UserInfo.getSessionId() を使用していますが、必要に応じて OAuth トークンを取得して使用することも可能です。

コメント