0

I want to send a rest api to my server and the content of the data need to be a string with double quote:

data=mycontent
curl -X POST "$SERVER_ENDPOINT" \
      -H 'Authorization: Bearer '"$SERVER_TOKEN"'' \
      -H "Content-Type: application/json" \
      --data '{"type":"TYPE1","name":"NAME1","content":"\"'$mycontent'"\"}' \
      | jq;

But I get an invalid json:

{
  "result": null,
  "success": false,
  "errors": [
    {
      "code": 9207,
      "message": "Content-type must be application/json."
    }
  ],
  "messages": []
}

How can I format a double quote string and send it thru rest api?

Kintarō
  • 2,947
  • 10
  • 48
  • 75
  • Use something that understands JSON, like `jq`, to create the data argument. See ["Build a JSON string with Bash variables"](https://stackoverflow.com/questions/48470049/build-a-json-string-with-bash-variables). – Gordon Davisson Jun 17 '22 at 08:09

1 Answers1

0

You were close. You only got confused with your Quotes.

'' at the end of Authorization Header is useless. It appends zero characters to the -H argument.

But the main issue is the data argument you provided:

'{"type":"TYPE1","name":"NAME1","content":"\"'$mycontent'"\"}'

would be parsed by the shell into the three Strings

  • {"type":"TYPE1","name":"NAME1","content":"\"
  • content of $mycontent unquoted
  • "\"} As you see, the " within the single Quotes were probably not what you wanted.

This should fix it:

curl -X POST "$SERVER_ENDPOINT" \
      -H 'Authorization: Bearer '"$SERVER_TOKEN" \
      -H "Content-Type: application/json" \
      --data '{"type":"TYPE1","name":"NAME1","content":"'"$mycontent"'"}' \
      | jq;

Debugging tip: Prefix the curl command with echo (and remove the | jq) if want to see how your quotes expand.

Security tip: Ensure, that $mycontent doesn't contain Quotes or backslashes. It could mess up your JSON.

entropie
  • 31
  • 3
  • thanks @entropie, but I want to have a double quote along with the string. That means one the server side I will see the "abcdef" instead of abcdef as my content. – Kintarō Jun 17 '22 at 12:56