问题
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