2

I am using CURL command line to send HTTP POST to a web service. I want to include a file's contents as a PART of the body of the POST command. Is this possible? I know I can send a file as the entire body as answered here. But I only want a part of the body to be the content of the file.

For example

curl -d '{ "name": "rahul", "speed": "fast", "data": { "number": 1, "letter": "abd", "letter2": "efg"} }' 'http://...'

Here I only want data as the file's content. Not the entire body. How can I do this?

b11
  • 67
  • 1
  • 1
  • 9

2 Answers2

1

Set a variable to contain the file contents:

data=$(cat /path/to/file)

then substitute it into the JSON:

curl -d '{ "name": "rahul", "speed": "fast", "data": "'$data'" }' 'http://...'
WolfSovereign
  • 27
  • 1
  • 6
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

You accepted @Barmar's answer, but for anyone reading this, @Barmar switched the double- and single-quotes, which will cause the command to not work as intended.

The following works:

data="$(cat filename)" && \
curl -d '{ "name": "rahul", "speed": "fast", "data": "'$data'" }' 'http://...'

Notice that the $data variable is surrounded by single-quotes first, then double-quotes.

tekknolagi
  • 10,663
  • 24
  • 75
  • 119
WolfSovereign
  • 27
  • 1
  • 6
  • does it matter if we are enclosing single quotes in double or vice versa ... ? I guess not as long as the other solution is working it does not matter. – anees May 07 '20 at 14:52
  • Well, if you have the wrong order the command won't work. I assume the answer was accepted because either the author switched the quotes on accident (therefore, it worked) or the author figured it out and didn't mention it. I have edited my answer, in order to clarify that @Barmar's answer is wrong – WolfSovereign May 07 '20 at 15:00
  • @WolfSovereign can you edit Barmar's answer so that it is correct? – gkubed May 07 '20 at 16:22
  • Will do, didn't know I could do that tbh, my bad. – WolfSovereign May 08 '20 at 07:05