在Lightning组件中(Aura或者LWC),使用Javascript通过Apex来调用RestAPI(执行SOQL 或者SOSL)
2023年10月08日
文章浏览:435
需求:在Lightning组件中(Aura或者LWC),通过Apex来调用RestAPI

有时候在开发Lightning组件的时候,需要调用RestAPI,

在这里我就和大家讲解怎么通过Javascript代码来调用Salesforce的RestAPI


第1步:创建一个名为GetSessionIdVF的Visualforce页面

GetSessionIdVF的代码如下

<apex:page >
  Start_Of_Session_Id{!$Api.Session_ID}End_Of_Session_Id
</apex:page>


第2步:创建一个名为getUserSessionId的Apex方法

Apex代码如下,

干的事情就是通过GetSessionIdVF页面,把SessionId给取出来。

public static String getUserSessionId(){
	String sessionId = '';
	// Refer to the Page
	PageReference reportPage = Page.GetSessionIdVF;
	
	// Get the content of the VF page
	String vfContent = reportPage.getContent().toString();
	
	System.debug('vfContent '+vfContent);
	
	// Find the position of Start_Of_Session_Id and End_Of_Session_Id
	Integer startP = vfContent.indexOf('Start_Of_Session_Id') + 'Start_Of_Session_Id'.length(),
	endP = vfContent.indexOf('End_Of_Session_Id');
	
	// Get the Session Id
	sessionId = vfContent.substring(startP, endP);
	
	System.debug('sessionId '+sessionId);
	
	// 返回Session Id的值
	return sessionId;
 }


第3步:创建一个名为makeAPICall的Apex方法

Apex代码如下(执行SOQL

@AuraEnabled
public static string makeAPICall(){
	String restMethod = '';

	String sessionId = getUserSessionId();

	HTTP h = new HTTP();
	HTTPRequest req = new HTTPRequest();
	HttpResponse resp = new HttpResponse();
	req.setMethod('GET');
	req.setHeader('Authorization', 'Bearer ' + sessionId);
	//这里就是通过Visualforce页面取得的SessionId,这个就是认证信息
	
    //下面就生成RestAPI的请求URL字符串
	req.setEndpoint(URL.getOrgDomainUrl().toExternalForm() + '/services/data/v53.0/query/?q=select+Id,Name+FROM+Account');

	resp = h.send(req);
	System.debug('#### Response Status '+resp.getStatus());
	System.debug('#### Response Status Code '+resp.getStatusCOde());
	System.debug(resp.getBody());

	return JSON.serialize(resp.getBody());
    
}


如果想执行SOSL,只需要把请求代码稍做修改就可以了。

String url =  URL.getSalesforceBaseUrl().toExternalForm() + '/services/data/v37.0/search/?q='+EncodingUtil.urlEncode('FIND {Sizhong} IN Name Fields RETURNING lead', 'UTF-8'); // use your own SOSL statement
req.setEndpoint(url);


下面就是makeAPICall执行的Debug。

58.0 APEX_CODE,DEBUG;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;NBA,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO;WAVE,INFO;WORKFLOW,INFO
20:50:03.0 (757365)|USER_INFO|[EXTERNAL]|0055h000004YWm7|yusizhong009@gmail.com|(GMT+09:00) Japan Standard Time (Asia/Tokyo)|GMT+09:00
20:50:03.0 (832954)|EXECUTION_STARTED
20:50:03.0 (844884)|CODE_UNIT_STARTED|[EXTERNAL]|apex://APICallForLightningComponent/ACTION$makeAPICall
20:50:03.0 (2070341)|CODE_UNIT_STARTED|[EXTERNAL]|01p5h00000TVTWN|APICallForLightningComponent.makeAPICall()
20:50:03.0 (208922550)|USER_DEBUG|[10]|DEBUG|vfContent 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head><script src="/static/111213/js/perf/stub.js" type="text/javascript"></script><script src="/jslibrary/1679071308244/sfdc/main.js" type="text/javascript"></script><script src="/jslibrary/jslabels/1696448644000/en_US.js" type="text/javascript"></script><link class="user" href="/sCSS/58.0/sprites/1687156602000/Theme3/default/gc/zen-componentsCompatible.css" rel="stylesheet" type="text/css" /><link class="user" href="/sCSS/58.0/sprites/1687156602000/Theme3/default/gc/elements.css" rel="stylesheet" type="text/css" /><link class="user" href="/sCSS/58.0/sprites/1687156602000/Theme3/default/gc/common.css" rel="stylesheet" type="text/css" /><link class="user" href="/sCSS/58.0/sprites/1691647034000/Theme3/gc/dStandard.css" rel="stylesheet" type="text/css" /><link class="user" href="/sCSS/58.0/sprites/1691647034000/Theme3/00D5h000004eQwI/0055h000004YWm7/gc/dCustom0.css" rel="stylesheet" type="text/css" /><link class="user" href="/sCSS/58.0/sprites/1687156602000/Theme3/default/gc/extended.css" rel="stylesheet" type="text/css" /><link class="user" href="/sCSS/58.0/sprites/1687156602000/Theme3/default/gc/setup.css" rel="stylesheet" type="text/css" /><script src="/jslibrary/1647410350244/sfdc/NetworkTracking.js" type="text/javascript"></script><script>try{ NetworkTracking.init('/_ui/networks/tracking/NetworkTrackingServlet', 'network', '0665h00000MgZ9D'); }catch(x){}</script><script>(function(UITheme) {
    UITheme.getUITheme = function() { 
        return UserContext.uiTheme;
    };
}(window.UITheme = window.UITheme || {}));</script></head><body>
  Start_Of_Session_IdSESSION_ID_REMOVEDEnd_Of_Session_Id</body></html>
20:50:03.0 (209195380)|USER_DEBUG|[16]|DEBUG|sessionId SESSION_ID_REMOVED
20:50:03.0 (211179678)|CALLOUT_REQUEST|[42]|
System.HttpRequest[Endpoint=https://dreamitschool-dev-ed.my.salesforce.com/services/data/v53.0/query/?q=select+Id,Name+FROM+Account, Method=GET]

20:50:03.0 (289004609)|CALLOUT_RESPONSE|[42]|System.HttpResponse[Status=OK, StatusCode=200]
20:50:03.0 (289154271)|USER_DEBUG|[43]|DEBUG|#### Response Status OK
20:50:03.0 (289212904)|USER_DEBUG|[44]|DEBUG|#### Response Status Code 200
20:50:03.0 (289477817)|USER_DEBUG|[45]|DEBUG|{"totalSize":26,"done":true,"records":[{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00001FxlszAAB"},"Id":"0015h00001FxlszAAB","Name":"RakutenWallet"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00001HDJIgAAP"},"Id":"0015h00001HDJIgAAP","Name":"株式会社NextStep"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00000dzhxcAAA"},"Id":"0015h00000dzhxcAAA","Name":"NextStepTraining"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h000012S2KfAAK"},"Id":"0015h000012S2KfAAK","Name":"SalesforceGogogo"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h000012S2NUAA0"},"Id":"0015h000012S2NUAA0","Name":"MyPartner"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00001HEg5oAAD"},"Id":"0015h00001HEg5oAAD","Name":"PayPay"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00001FyJ8yAAF"},"Id":"0015h00001FyJ8yAAF","Name":"NameTest"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00000dzhxhAAA"},"Id":"0015h00000dzhxhAAA","Name":"NextStepのCustomer"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00000ZDeKaAAL"},"Id":"0015h00000ZDeKaAAL","Name":"GenePoint"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00000ZDeKYAA1"},"Id":"0015h00000ZDeKYAA1","Name":"United Oil & Gas, UK"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00000ZDeKZAA1"},"Id":"0015h00000ZDeKZAA1","Name":"United Oil & Gas, Singapore"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00000ZDeKQAA1"},"Id":"0015h00000ZDeKQAA1","Name":"Edge Communications"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00000ZDeKRAA1"},"Id":"0015h00000ZDeKRAA1","Name":"Burlington Textiles Corp of America"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00000ZDeKSAA1"},"Id":"0015h00000ZDeKSAA1","Name":"Pyramid Construction Inc."},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00000ZDeKTAA1"},"Id":"0015h00000ZDeKTAA1","Name":"Dickenson plc"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00000QAQxNAAX"},"Id":"0015h00000QAQxNAAX","Name":"エンタイトルメントの取引先のサンプル"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00000ZDeKUAA1"},"Id":"0015h00000ZDeKUAA1","Name":"Grand Hotels & Resorts Ltd"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00000ZDeKWAA1"},"Id":"0015h00000ZDeKWAA1","Name":"Express Logistics and Transport"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00000ZDeKXAA1"},"Id":"0015h00000ZDeKXAA1","Name":"University of Arizona"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00000ZDeKVAA1"},"Id":"0015h00000ZDeKVAA1","Name":"United Oil & Gas Corp."},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00000ZDeKbAAL"},"Id":"0015h00000ZDeKbAAL","Name":"sForce"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00000dzTJ7AAM"},"Id":"0015h00000dzTJ7AAM","Name":"PartnerAccount"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00001FyIdUAAV"},"Id":"0015h00001FyIdUAAV","Name":"Name"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00001FxlskAAB"},"Id":"0015h00001FxlskAAB","Name":"RakutenMobile"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00001HEeJcAAL"},"Id":"0015h00001HEeJcAAL","Name":"兪テスト"},{"attributes":{"type":"Account","url":"/services/data/v53.0/sobjects/Account/0015h00001FxlsQAAR"},"Id":"0015h00001FxlsQAAR","Name":"yusizhong"}]}
20:50:03.292 (292146588)|CUMULATIVE_LIMIT_USAGE
20:50:03.292 (292146588)|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 0 out of 100
  Number of query rows: 0 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 0 out of 150
  Number of Publish Immediate DML: 0 out of 150
  Number of DML rows: 0 out of 10000
  Maximum CPU time: 11 out of 10000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 1 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 50
  Number of Mobile Apex push calls: 0 out of 10

20:50:03.292 (292146588)|CUMULATIVE_LIMIT_USAGE_END

20:50:03.0 (292289702)|CODE_UNIT_FINISHED|APICallForLightningComponent.makeAPICall()
20:50:03.0 (293242508)|CODE_UNIT_FINISHED|apex://APICallForLightningComponent/ACTION$makeAPICall
20:50:03.0 (293254242)|EXECUTION_FINISHED


第4步:在Lightning组件中,调用makeAPICallApex方法

代码如下,

callAction2: function(cmp, apiName, param) {
    console.log("CallAPI2----------->"); 
      
    return new Promise($A.getCallback(function(resolve, reject) {
      var action = cmp.get("c.makeAPICall");
     
      // レスポンスの処理
      action.setCallback(this, function(response) {
        const state = response.getState();

        if (state == 'SUCCESS') {
          resolve(response.getReturnValue());
        }
        else {
          reject(response.getError());
        }
      });
      
      $A.enqueueAction(action);
    }));
},



参考文章

Rest API call from apex Controller

 https://salesforce.stackexchange.com/questions/186742/rest-api-call-from-apex-controller 


Salesforce Lightning: How can i get session Id of current user in Salesforce lightning component?

https://salesforce.stackexchange.com/questions/223809/salesforce-lightning-how-can-i-get-session-id-of-current-user-in-salesforce-lig 


can we query SOSL using REST API?

https://salesforce.stackexchange.com/questions/158477/can-we-query-sosl-using-rest-api


Search for a String

https://developer.salesforce.com/docs/atlas.en-us.244.0.api_rest.meta/api_rest/dome_search.htm


Execute a SOQL Query

https://developer.salesforce.com/docs/atlas.en-us.244.0.api_rest.meta/api_rest/dome_query.htm


关注 收藏