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?
GraphQL responses are in JSON. Every response is a JSON map, and will include JSON keys for "data" , "errors" , or "extensions" following the GraphQL specification. They follow the following formats. Queries that have errors are in the following format.
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.
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)"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With