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 求糕手!用matlab求解目标规划模型🙏
  • ¥15 画出的分类图不对,求解答一下
  • ¥20 springboot和springcloud版本问题
  • ¥15 ps2手柄控制树莓派小车
  • ¥30 C#:vsto powerpoint的外接程序
  • ¥30 stata将do文件代码转化为ado文件
  • ¥15 两个同维数组相比,不同位置、出现重复比无意义,而不同位置、不出现重复比,则有意义。把有意义的两个数组放入新的集合MK中。
  • ¥15 可以远程电脑安装nvm
  • ¥15 写一个可直接调用的函数,将32位有符号数转成另一个无符号的数
  • ¥15 CMAKE+VS2019+QT5.15.2组合进行二次编译