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

PowerShell中Invoke-RestMethod调用API时API Key授权失败

API密钥授权问题排查(PowerShell调用失败,Postman可成功)

我尝试调用某API时遇到API Key类型的授权问题,导致调用失败。Postman中可正常调用该API(附截图),但以下PowerShell代码无法正常运行:

$headers = @{Authorization="auth_token codeKeyhere"}
$params = @{
    Uri         = 'endopointhere'
    Method      = 'GET'
    ContentType = 'application/json'
}

$response =  Invoke-RestMethod @params -Header $header
$response

问题排查与修正方案

  • 变量名拼写错误:代码中定义的请求头变量是$headers,但调用Invoke-RestMethod时写的是-Header $header(少了末尾的s),这会导致授权头未正确传递。
  • 请求头传递方式优化:可以直接将Headers加入参数哈希表,避免单独传递时的拼写失误。
  • 验证授权头格式:确认Postman中使用的auth_token codeKeyhere格式完全匹配API要求,部分API可能要求Bearer前缀或其他格式,需严格对齐Postman的请求头内容。

修正后的代码示例

$headers = @{Authorization="auth_token codeKeyhere"}
$params = @{
    Uri         = 'endopointhere'
    Method      = 'GET'
    ContentType = 'application/json'
    Headers     = $headers
}

$response = Invoke-RestMethod @params
$response

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:41:08