duannaoben8011 2019-04-07 23:56 采纳率: 0%
浏览 371
已采纳

使用HTTP客户端通过graphql传递变量

I'm trying to interface with shopify storefront api in golang. But this is my first encounter with graphql and I'm a bit confused.

I need to pass variables for the request and did some research where I came to the conclusion that I could pass variables like shown below. But shopify keeps returning this error:

{"errors":[{"message":"Parse error on \"variables\" (IDENTIFIER) at [13, 3]","locations":[{"line":13,"column":3}]}]}

Here is my current code:

body := strings.NewReader(fmt.Sprintf(`
    mutation ($checkoutId: ID!, $lineItems: [CheckoutLineItemInput!]!) {
        checkoutLineItemsAdd(checkoutId: $checkoutId, lineItems: $lineItems) {
          userErrors {
            message
            field
          }
          checkout {
            id
          }
        }
      }
    variables: { "lineItems": [ { "quantity": 1, "variantId": "%s" } ], "checkoutId": "%s" }
`, productID, checkoutID))

req, err := http.NewRequest("POST", "https://myshop.myshopify.com/api/graphql", body)
if err != nil {
    // handle err
    fmt.Println(err)
}
req.Header.Set("Content-Type", "application/graphql")
req.Header.Set("X-Shopify-Storefront-Access-Token", "mytoken")

resp, err := http.DefaultClient.Do(req)
if err != nil {
    // handle err
    fmt.Println(err)
}
defer resp.Body.Close()

data, err := ioutil.ReadAll(resp.Body)
if err != nil {
    // handle err
    fmt.Println(err)
}

My question is, what is the correct way of passing variables when using application/graphql?


After updating the code with the answer of @DanielRearden I'm now getting this error:

{"errors":[{"message":"Variable checkoutId of type ID! was provided invalid value","locations":[{"line":1,"column":11}],"extensions":{"value":null,"problems":[{"path":[],"explanation":"Expected value to not be null"}]}},{"message":"Variable lineItems of type [CheckoutLineItemInput!]! was provided invalid value","locations":[{"line":1,"column":29}],"extensions":{"value":null,"problems":[{"path":[],"explanation":"Expected value to not be null"}]}}]}

Updated code:

    body := strings.NewReader(fmt.Sprintf(`{
        "query": "mutation ($checkoutId: ID!, $lineItems: [CheckoutLineItemInput!]!) { checkoutLineItemsAdd(checkoutId: $checkoutId, lineItems: $lineItems) { userErrors { message field } checkout { id } }}",
        "variables": { 
            "$lineItems": [ 
                { "quantity": 1, "variantId": "%s" }
            ], 
            "$checkoutId": "%s"
        }
    }`, productID, checkoutID))
    ...
    ...
    req.Header.Set("Content-Type", "application/json")

Removing the $ token on the variables as shown below returns another error:

{
        "query": "mutation ($checkoutId: ID!, $lineItems: [CheckoutLineItemInput!]!) { checkoutLineItemsAdd(checkoutId: $checkoutId, lineItems: $lineItems) { userErrors { message field } checkout { id } }}",
        "variables": { 
            "checkoutId": "%s",
            "lineItems": [ 
                { "quantity": 1, "variantId": "%s" }
            ]
        }
    }

And the error is: (status 500)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="referrer" content="never" />
  <title>Something went wrong</title>

But I guess this is not a graphql issue anymore but more of a shopify api problem.

  • 写回答

1条回答 默认 最新

  • droi5225 2019-04-08 00:23
    关注

    You can't use variables when you set the Content Type to application/graphql because the entire request body is treated as a single GraphQL document. Variables cannot be included inside a GraphQL document -- they have to be submitted separately. Instead of using application/graphql, you should use application/json as the Content Type. Then, your request body should be a JSON string with two keys -- query and variables:

    {
      "query": "mutation ($checkoutId: ID!, $lineItems: [CheckoutLineItemInput!]!) {...}",
      "variables": {
        "checkoutId" "",
        "lineItems": [
          ...
        ]
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀