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

GraphQL查询在Postman有效但cURL请求报400格式错误求助

解决GraphQL查询在cURL中返回400格式错误的问题

问题背景

一段GraphQL查询在Postman中测试正常,但通过cURL发起请求时始终返回400格式错误,相关查询与cURL命令如下:

有效GraphQL查询

query {
  products {
    complexity
    request_id
    data(first: 100) {
      edges {
        node {
        id
        sku
        name
        warehouse_products {
          id 
          warehouse_id
          on_hand
        }
      }
    }
  }
}

报错的cURL命令

curl -v -X POST -H "Content-Type: application/json" -H "Accept: application/json" -H "Authorization: Bearer xxxxxxxxxxxxxx" --data '{"query":"query { products { complexity request_id data(first: 100) { edges { node { id sku name warehouse_products { id warehouse_id on_hand}}}}}}"}' https://public-api.shiphero.com/graphql

问题原因

cURL的--data参数默认会对请求内容做URL编码,可能破坏GraphQL查询的原始结构;同时直接在shell中拼接JSON字符串时,容易出现隐性的引号解析或格式转义问题。

解决方案

方案1:用--data-raw替代--data

--data-raw不会对内容做URL编码,能完整保留GraphQL查询的格式:

curl -v -X POST \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -H "Authorization: Bearer xxxxxxxxxxxxxx" \
  --data-raw '{"query":"query { products { complexity request_id data(first: 100) { edges { node { id sku name warehouse_products { id warehouse_id on_hand}}}}}}"}' \
  https://public-api.shiphero.com/graphql

方案2:将查询写入文件传递(推荐,易维护)

  1. 创建product-query.graphql文件,写入你的GraphQL查询:
query {
  products {
    complexity
    request_id
    data(first: 100) {
      edges {
        node {
          id
          sku
          name
          warehouse_products {
            id 
            warehouse_id
            on_hand
          }
        }
      }
    }
  }
}
  1. 使用cURL读取文件并构造请求:
curl -v -X POST \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -H "Authorization: Bearer xxxxxxxxxxxxxx" \
  --data "$(jq -n --arg query "$(cat product-query.graphql)" '{query: $query}')" \
  https://public-api.shiphero.com/graphql

方案3:用Here-Doc传递完整JSON(可读性强)

直接保留GraphQL查询的换行和缩进,避免手动压缩:

curl -v -X POST \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -H "Authorization: Bearer xxxxxxxxxxxxxx" \
  --data @- <<EOF
{
  "query": "query {
    products {
      complexity
      request_id
      data(first: 100) {
        edges {
          node {
            id
            sku
            name
            warehouse_products {
              id 
              warehouse_id
              on_hand
            }
          }
        }
      }
    }
  }"
}
EOF

验证要点

  • 确认Authorization头中的Bearer令牌有效
  • 确保Content-Type头为application/json,这是GraphQL服务接收JSON请求的必要条件
  • 检查查询语法(已在Postman验证,可排除此问题)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 17:30:21