如何在Power Query中用带请求头和请求体的Web.Contents实现两步API调用?
在Power Query中实现两步API请求流程
第一步:获取并存储ReportID
Power Query中通过Web.Contents函数发送带请求体的POST请求,需配置Headers(请求头)和Content(请求体)参数,示例代码如下:
let // 配置请求头,按API要求调整字段 RequestHeaders = [ #"Content-Type" = "application/json", #"Authorization" = "Bearer your_auth_token" // 按需添加授权信息 ], // 构造请求体,替换为实际的日期、gameTitle等参数 RequestBody = Json.FromValue([ date = "2024-05-20", gameTitle = "TargetGame" ]), // 发送POST请求获取ReportID RawReportIDResp = Web.Contents("https://your-api-domain.com/api/get-report-id", [ Headers = RequestHeaders, Content = RequestBody, ManualStatusHandling = {400, 401, 500} // 按需添加需要手动处理的状态码 ]), // 解析返回的JSON数据 ParsedResp = Json.Document(RawReportIDResp), // 提取ReportID并存储为变量 ReportID = ParsedResp[reportId] in ReportID
第二步:用ReportID请求主报告
可将第一步逻辑直接串联到同一个查询中,或引用已保存的第一步查询结果,示例代码如下:
let // --- 第一步逻辑复用 --- RequestHeaders = [ #"Content-Type" = "application/json", #"Authorization" = "Bearer your_auth_token" ], RequestBody = Json.FromValue([ date = "2024-05-20", gameTitle = "TargetGame" ]), RawReportIDResp = Web.Contents("https://your-api-domain.com/api/get-report-id", [ Headers = RequestHeaders, Content = RequestBody ]), ParsedResp = Json.Document(RawReportIDResp), ReportID = ParsedResp[reportId], // --- 主报告请求逻辑 --- // 构造主报告请求地址,按API要求传递ReportID(示例为GET参数形式) MainReportUrl = "https://your-api-domain.com/api/get-main-report?reportId=" & ReportID, // 发送请求获取主报告 RawMainReport = Web.Contents(MainReportUrl, [ Headers = RequestHeaders ]), // 解析主报告JSON数据 ParsedMainReport = Json.Document(RawMainReport) in ParsedMainReport
关键注意点
Content参数需为二进制格式,JSON类型请求体必须用Json.FromValue转换;若为form-data格式,改用FormData.FromRecords处理。- 若需复用ReportID变量,直接在
let-in结构内串联步骤即可,也可将第一步保存为独立查询,第二步通过=#"第一步查询名称"引用。 - 注意匹配Python代码中的请求头配置(如授权、Content-Type),避免权限或格式错误。
- 若遇到刷新异常,检查Power Query的数据源隐私设置,或在
Web.Contents中显式声明Query参数。
内容的提问来源于stack exchange,提问作者noob_taxer
相关产品推荐
相关产品推荐

