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:将查询写入文件传递(推荐,易维护)
- 创建
product-query.graphql文件,写入你的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 "$(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
相关产品推荐
相关产品推荐

