【问题标题】:Unable to execute GraphQL mutation using cURL无法使用 cURL 执行 GraphQL 突变
【发布时间】:2021-01-13 02:16:11
【问题描述】:

我已经在 MicroProfile 容器 (WildFly) 中部署了一个 Mutation,并且能够在 GraphQL UI 中执行它:

mutation Add {
  createOrder(order: {
      id: 1,
      type: "car"
      model: "Ferrari"
      price: 500
    }
  )
  {
    type
    model
    price
  }
}

但是,当我尝试使用 cURL 执行相同的突变时:

curl \
  -X POST \
  -H "Content-Type: application/json" \
  --data '{ "query": "mutation Add {
  createOrder(order: {
      id: 1,
      type: \"car\"
      model: \"Ferrari\"
      price: 500
    }
  )
  {
    type
    model
    price
  }
}
" }' http://localhost:8080/demo/graphql

但是它失败了:

javax.json.stream.JsonParsingException: Unexpected char 10 at (line no=1, column no=27, offset=26)

我没有找到很多使用命令行工具(如 cURL)运行 Mutation 的示例,也不知道错误在哪里。有什么帮助吗? 谢谢

【问题讨论】:

  • 会不会像 shell 吃掉你的反斜杠一样简单?尝试记录到达您服务器的确切有效负载。

标签: graphql graphql-java


【解决方案1】:

您正在通过 curl 发送 json 数据,而 Json 规范不允许换行。它们需要替换为 '\n' 字符。

curl \
  -X POST \
  -H "Content-Type: application/json" \
  --data '{ "query": "mutation Add { createOrder(order: {id: 1, type: \"car\", model: \"Ferrari\", price: 500}){type\n model\n price\n}}" }' http://localhost:8080/demo/graphql

有关其他建议,请参阅此问题:Correct format for multiline '--data' in curl query to graphql endpoint?

【讨论】:

    【解决方案2】:

    在这里,我使用 curl、换行符转义和缩进进行了工作突变。它确实看起来并不花哨,但比 oneliner 更易于维护:https://stackoverflow.com/a/65837497/835098

    我已经重新格式化了您的 curl 调用,现在应该可以使用了。注意输入和输出参数很好地为您的突变缩进。您只需要担心在每行末尾添加反斜杠并转义“查询”字符串中的反斜杠和引号。

    哦,别忘了在每个输入参数后添加逗号。我认为您的原始请求中缺少这些。

    curl \
      -X POST \
      -H "Content-Type: application/json" \
      --data \
    "{ \
        \"query\": \"mutation Add { \
            createOrder(order: { \
                id: 1, \
                type: \\\"car\\\", \
                model: \\\"Ferrari\\\", \
                price: 500 \
            }){ \
                type \
                model \
                price \
            } \
        } \
    } \
    " http://localhost:8080/demo/graphql
    

    【讨论】:

      猜你喜欢
      • 2021-08-05
      • 2019-02-21
      • 2017-06-07
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 2019-12-23
      • 2020-08-15
      • 2021-05-11
      相关资源
      最近更新 更多