Salesforce GraphQL API调用问题:Apex调用报Session ID无效求助
Salesforce GraphQL API调用问题解决
问题原因
你遇到的「Session ID not valid for Rest API」错误,是因为LWC调用Apex时,UserInfo.getSessionId()获取的是前端Lightning会话ID,这个ID仅适用于Lightning界面上下文,不能直接用于REST/GraphQL API调用;而开发者控制台运行Apex时处于API上下文,拿到的Session ID是API专用的,所以可以正常工作。
解决方案
方案1:使用Salesforce官方封装的GraphQL Apex类
这是最推荐的方式,官方已经帮你处理了认证和请求细节,无需手动管理Session ID。修改你的Apex代码如下:
public with sharing class GraphQLContactController { @AuraEnabled(cacheable=true) public static String getContacts() { GraphQL graphql = new GraphQL(); // 直接写标准GraphQL语法,无需额外转义 String query = '{ uiapi { query { Contact { edges { node { Id Name { value } } } } } }'; GraphQLResponse response = graphql.execute(query); return response.getJSONObject().toString(); } }
在LWC中调用这个AuraEnabled方法即可,不会出现认证问题。
方案2:修改HTTP请求代码,移除手动设置的Authorization头
如果一定要用HTTP请求方式,不要手动设置Authorization头——Apex调用内部Salesforce API时,系统会自动以当前用户身份完成认证,不需要手动传Session ID。修改后的代码:
@AuraEnabled(cacheable=true) public static String getContactsViaHttp() { String endpoint = '/services/data/v52.0/graphql'; HttpRequest request = new HttpRequest(); request.setEndpoint(endpoint); request.setMethod('POST'); request.setHeader('Content-Type', 'application/json'); // 修正原代码的引号嵌套错误,避免JSON解析失败 request.setBody('{"query": "{ uiapi { query { Contact { edges { node { Id Name { value } } } } } }"}'); Http http = new Http(); HTTPResponse response = http.send(request); return response.getBody(); }
方案3:使用LWC官方GraphQL Wire适配器
如果之前尝试lightning/uiGraphQLApi适配器失败,检查以下几点后重试:
- 已正确导入适配器模块
- 用户Profile开启了「API Enabled」和「GraphQL API Enabled」权限
- 查询语法正确、目标字段有访问权限
示例代码:
import { wire, api } from 'lwc'; import { graphql } from 'lightning/uiGraphQLApi'; // 标准GraphQL查询字符串,无需额外转义 const CONTACT_QUERY = ` { uiapi { query { Contact { edges { node { Id Name { value } } } } } } } `; export default class ContactListGraphQL extends LightningElement { @wire(graphql, { query: CONTACT_QUERY }) contacts; // 格式化返回的联系人数据 get contactList() { return this.contacts.data?.uiapi?.query?.Contact?.edges?.map(edge => edge.node) || []; } }
内容的提问来源于stack exchange,提问作者Jenil
相关产品推荐
相关产品推荐

