Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

curl

graphql

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?

like image 627
hal497 Avatar asked Nov 25 '18 16:11

hal497


People also ask

Is GraphQL query JSON?

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.


2 Answers

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.

like image 127
David Maze Avatar answered Oct 17 '22 18:10

David Maze


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)"
like image 2
Ivan Avatar answered Oct 17 '22 17:10

Ivan