Correct format for multiline '--data' in curl query to graphql endpoint?

99封情书 提交于 2021-01-27 07:11:59

问题


I'm passing "--data" via curl to a GraphqQL API endpoint.

I want to be able to pass the data in 'prettified' form, e.g. as in GraphiQL browser,

{
  alpha {
    param1
    param2
  }
}

Atm, my formatting inside the data -- namely, re: line returns -- isn't handled properly.

This single-line-string form works,

curl \
 -H 'content-type: application/json' \
 -X POST /path/to/graphql/api/endpoint \
 --data '{ "query":
           "query { alpha {param1, param2} } "
         }'

This 'prettified' version does not

curl \
 -H 'content-type: application/json' \
 -X POST /path/to/graphql/api/endpoint \
 --data '{ "query":
           "query {
              alpha {
                param1
                param2
              }
            } "
         }'

What's the right syntax for passing the 2nd form?

I'm guessing some combination of quoting/escaping?


回答1:


Newlines just aren't allowed inside JSON strings. (See RFC 8259 §7, which states that control characters must be escaped.) You can turn a newline into \n, but that gets a little unwieldy:

curl \
 -H 'content-type: application/json' \
 -X POST /path/to/graphql/api/endpoint \
 --data '{ "query":
           "query {\n  alpha {\n    param1\n    param2\n  }\n} "
         }'

Since the JSON queries are pretty well-structured, it seems to work better to use a dedicated tool for submitting GraphQL queries: the standalone version of GraphiQL is an okay default, or if you have a favorite scripting language with a reasonable HTTP client it's easy enough to write something with that.




回答2:


Something along the lines of this:

QUERY='{ "query":
           "query {
              alpha {
                param1
                param2
              }
            } "
         }'
curl \
 -H 'content-type: application/json' \
 -X POST /path/to/graphql/api/endpoint \
 --data "$(echo $QUERY)"


来源:https://stackoverflow.com/questions/53469321/correct-format-for-multiline-data-in-curl-query-to-graphql-endpoint

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!