You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel/PBI中PowerQuery发送带请求体的POST API请求报400错误

解决PowerQuery中POST API返回400 Bad Request的问题

我在Excel/PBI的PowerQuery里调用API发送带请求体的POST请求,一直收到报错:DataSource.Error: Web.Contents无法获取'https://myapi.com/data'的内容(400): Bad Request,但在Postman里调用完全正常。

第一种尝试的代码

let
    Source = Json.Document(Web.Contents("https://myapi.com/data", [Headers=[#"X-Impersonate-User"="usr_12345", Authorization="Bearer tok_12345", #"Content-Type"="application/json"], 
    
    Content=Json.FromValue({[start_date="2022-08-01T08:00:00.000Z", end_date="2022-08-10T08:00:00.000Z", space_ids="spc_12345", time_resolution="day"]})


    ]))
in
    Source

第二种尝试的代码

let 
    url = "https://myapi.com/data"
    body = "{"start_date" : "2022-08-01T08:00:00.000Z", "end_date" : "2022-08-10T08:00:00.000Z", "space_ids" : "spc_12345", "time_resolution" : "day"}",
    Parsed_JSON = Json.Document(body),
    BuildQueryString = Uri.BuildQueryString(Parsed_JSON),
    Source = Json.Document(Web.Contents(url,[Headers=[#"Content-Type"="application/json", #"X-Impersonate-User"="usr_12345", Authorization="Bearer Bearer tok_12345"], Content = Text.ToBinary(BuildQueryString) ] ))
in
    Source

问题原因分析

  1. 第一种代码里,Json.FromValue包裹了数组{[...]},但Postman中的请求体大概率是单个对象而非数组,API无法识别数组格式的请求体,直接返回400错误。
  2. 第二种代码存在两处明显错误:
    • Authorization头重复写了两次Bearer(Bearer Bearer tok_12345),格式不符合要求;
    • 用Uri.BuildQueryString把JSON转成了查询字符串格式,但请求头声明的是application/json,API期望JSON格式的请求体,格式不匹配导致报错。

修正后的代码

let
    url = "https://myapi.com/data",
    // 构造与Postman一致的请求体对象(非数组)
    requestBody = [
        start_date = "2022-08-01T08:00:00.000Z",
        end_date = "2022-08-10T08:00:00.000Z",
        space_ids = "spc_12345",
        time_resolution = "day"
    ],
    // 将对象转为二进制JSON格式
    content = Json.FromValue(requestBody),
    // 设置正确的请求头,Authorization格式无冗余
    headers = [
        #"X-Impersonate-User" = "usr_12345",
        Authorization = "Bearer tok_12345",
        #"Content-Type" = "application/json"
    ],
    // 发送请求并解析响应
    response = Web.Contents(url, [Headers=headers, Content=content]),
    Source = Json.Document(response)
in
    Source

额外验证建议

  • 打开Postman的请求详情页,对比请求体结构,确保PowerQuery里的requestBody和Postman完全一致;
  • 检查Postman中的所有请求头,把缺失的键值对同步到PowerQuery的headers里;
  • 如果仍有问题,可以在PowerQuery中开启Web请求的日志,对比Postman的请求参数,定位差异。

内容的提问来源于stack exchange,提问作者CESBoston

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:45:44