I have the following script that works perfectly:
payload='{"index":{}}'$'\n''{"name":"Samuel"}'
echo "$payload" > tmp.json
curl -X POST "http://my.api.com/" \
-H "Content-Type: application/json" \
--data-binary @./tmp.json
I get a success response from my.api.com and I confirmed the entry made it into the database.
I don’t like that I am writing a tmp.json to disk. I prefer to send the payload variable as is directly to the curl statement. So I tried something like this:
payload='{"index":{}}'$'\n''{"name":"Samuel"}'
curl -X POST "http://my.api.com/" \
-H "Content-Type: application/json" \
--data @- << echo "$payload"
But I get an error response from my.api.com saying there are line break issues and syntax issues. What Can I do to avoid writing the payload variable to disk?
I’ve tried many other things like:
--data "$payload"
--data `$payload`
--data @<(echo "$payload")
...etc...
But none of these are working.
>Solution :
<< is for here documents:
curl ... <<EOF
$payload
EOF
You want either a process substitution
curl ... < <(echo "$payload")
or a here string
curl ... <<< "$payload"
But if you already have the payload in a parameter, you don’t need @- anymore:
curl ... --data "$payload"
I’m not sure why that would be producing the error you claim.