execute curl command in ruby code - jruby

i am trying to run following curl command from my ruby code
Kernel.system'curl -H "Content-Type:application/json" -H "Accept:application/json" -d "{\"project\":{\"name\":\"BB\",\"description\":\"Book\"}}" "http://localhost:3000/company/projects?auth_token=mRFWyxfdPKHsDb4HhyLP"'
I want to do something like
name = "BB"(using a variable)
and then executing
Kernel.system'curl -H "Content-Type:application/json" -H "Accept:application/json" -d "{\"project\":{\"name\":"#{name}",\"description\":\"Book\"}}" "http://localhost:3000/company/projects?auth_token=mRFWyxfdPKHsDb4HhyLP"'
but this approach is not working...its taking #{name} as string.
Please help me with this.Let me know if i am doing something wrong.
Thanks.

in order to enable string interpolation you will need to use double quotes in your string. The topic has been covered here: Double vs single quotes
also it would make your code better to read if you refactored it and assigned the parts to variables before joining them together into one string.
so:
host_name = 'stackoverflow.com'
Kernel.system 'curl -I #{host_name}'
will not work
whereas
Kernel.system "curl -I #{host_name}"
will

Related

JSON format error thrown by cUrl but not Wget?

I am sending a POST request via a batch script on Windows. I have manually installed wget and all works fine, but I'd like to use cUrl as it recently became a Windows 10 standard feature and can be run on other newer computers. The problem is that cUrl throws a Json formatting error despite not seeming to have any special character exceptions.
I've tried changing quotations to apostrophes and vice versa, and using backslashes and carets as escape characters. This wget script works:
wget --quiet ^
--method POST ^
--header 'content-type: application/json' ^
--body-data '{"method":"passthrough", "params": {"deviceId": "[MyId]", "requestData": "{\"system\":{\"set_relay_state\":{\"state\":0}}}" }}' ^
--output-document ^
- 'https://eu-wap.tplinkcloud.com/?token=[MyToken]'
However the exact same JSON in cUrl is refused:
curl -X POST -H 'content-type:application/json' -d '{"method":"passthrough","params":{"deviceId":"[MyId]","requestData":"{\"system\":{\"set_relay_state\":{\"state\":0}}}"}}' https://wap.tplinkcloud.com?token=[MyToken]
Thanks for any advice.
You are using the curl (C:\Windows\System32\curl.exe) at Windows 10 on the command line for Windows.
If my understanding is correct, how about this modification?
Modified curl command for Windows:
curl -H "content-type:application/json" -d "{\"method\":\"passthrough\",\"params\":{\"deviceId\":\"[MyId]\",\"requestData\":\"{\\\"system\\\":{\\\"set_relay_state\\\":{\\\"state\\\":0}}}\"}}" https://eu-wap.tplinkcloud.com/?token=[MyToken]
At Windows command line, please use the double quotes instead of the single quotes.
At JSON object, please escape each double quotes.
Note:
I'm not sure about the correct URL from your reply. So please use the correct URL when you test above.
I'm also using Curl on windows and kept getting JSON Error,
I switched the single and double quotes and it worked fine
curl -H "Content-Type:application/json" -H "Authorization:Bearer <token>" -d "{'fileid':'<fileid>','printerid':'<printerid>','type':'pdf'}" "https://printapi.ezeep.com/sfapi/Print"

cURL throwing globbing error when JSON data in variable contains a space

Using bash v4.3.48(1) on Ubuntu 16.04.2 LTS and bash v3.2.57 on macOS Sierra 10.12.5 I have this code which POSTs JSON data stored in a variable:
#1
JSON_DATA="Test"; \
curl -X POST "https://www.techotaku.com/json.php" \
-H "Content-Type: application/json" \
-d '{"data":"'$JSON_DATA'"}'
This returns:
Array
(
[data] => Test
)
However, if $JSON_DATA contains a space...
#2
JSON_DATA="A Test"; \
curl -X POST "https://www.techotaku.com/json.php" \
-H "Content-Type: application/json" \
-d '{"data":"'$JSON_DATA'"}'
...it throws an error:
curl: (3) [globbing] unmatched close brace/bracket in column 6
I thought this might be due to incorrect use of quotes, but if I echo the JSON data...
echo '{"data":"'$JSON_DATA'"}'
...it appears well-formed:
{"data":"A Test"}
Also, if I include the JSON data as a string and not a variable, it works.
#3
curl -X POST "https://www.techotaku.com/json.php" \
-H "Content-Type: application/json" \
-d '{"data":"A Test"}'
The only way I can get it to work if the variable contains a space is to enclose the JSON data in double-quotes and escape the literal double-quotes in the string:
#4
JSON_DATA="A Test"; \
curl -X POST "https://www.techotaku.com/json.php" \
-H "Content-Type: application/json" \
-d "{\"data\":\"$JSON_DATA\"}"
I would have thought that all 4 examples would have worked. So, can anyone throw any light on why only examples 1,3 and 4 work and example 2 doesn't?
Many thanks, Steve.
You should quote your variables to prevent word splitting by shell. Your second example:
'{"data":"'$JSON_DATA'"}'
doesn't work because it's being expanded by bash to two words:
{"data":"A Test"}
so -d option receives 2 arguments ({"data":"A and Test"}). If JSON_DATA contained globbing metacharacters, those would cause filename expansion.
To fix it, quote it:
'{"data":"'"$JSON_DATA"'"}'
Note the use of alternating single and double quotes. This will be expanded to a single word:
{"data":"A Test"}
Here's a more detailed answer I wrote some time ago which also mentions another convenient option, the use of a here-document.

Why do I get a malformed JSON in request body in this cURL call?

I have been trying to call the CloudFlare API v4, using an example provided in their own documentation.
This is the code of the example
curl -X PUT "https://api.cloudflare.com/client/v4/zones/023e105f4ecef8ad9ca31a8372d0c353/dns_records/372e67954025e0ba6aaa6d586b9e0b59" \ -H "X-Auth-Email: user#example.com" \ -H "X-Auth-Key: c2547eb745079dac9320b638f5e225cf483cc5cfdda41" \ -H "Content-Type: application/json" \ --data '{"id":"372e67954025e0ba6aaa6d586b9e0b59","type":"A","name":"example.com","content":"1.2.3.4","proxiable":true,"proxied":false,"ttl":120,"locked":false,"zone_id":"023e105f4ecef8ad9ca31a8372d0c353","zone_name":"example.com","created_on":"2014-01-01T05:20:00.12345Z","modified_on":"2014-01-01T05:20:00.12345Z","data":{}}'
Which can also be found at
Update DNS Records
Using Windows cmd.exe to run this command, I need to make it single line first, so I removed the "" and reformatted it (twice) making sure I altered no part in the process.
This is the same code in one line:
curl -X PUT "https://api.cloudflare.com/client/v4/zones/023e105f4ecef8ad9ca31a8372d0c353/dns_records/372e67954025e0ba6aaa6d586b9e0b59" -H "X-Auth-Email: user#example.com" -H "X-Auth-Key: c2547eb745079dac9320b638f5e225cf483cc5cfdda41" -H "Content-Type: application/json" --data '{"id":"372e67954025e0ba6aaa6d586b9e0b59","type":"A","name":"example.com","content":"1.2.3.4","proxiable":true,"proxied":false,"ttl":120,"locked":false,"zone_id":"023e105f4ecef8ad9ca31a8372d0c353","zone_name":"example.com","created_on":"2014-01-01T05:20:00.12345Z","modified_on":"2014-01-01T05:20:00.12345Z","data":{}}'
When I run this single-liner in cmd, it works but I get a malformed JSON in request body, however, a visual check, formatting on Notepad++ and a run through the JSON validator are all positive, this JSON (copied from the CloudFlare documentation) is not malformed.
Error Message
{"success":false,"errors":[{"code":6007,"message":"Malformed JSON in request body"}],"messages":[],"result":null}
Googling this error message or the error code gives me nothing and this same command works on a PC running Linux.
Can someone tell me if this is a known bug, if the JSON really is malformed or if something else comes to mind?
I found the answer in the blog post: "Expecting to find valid JSON in request body..." curl for Windows.
For example, for Purge everything --data value will be:
# On Linux
--data '{"purge_everything":true}'
# On Windows
--data "{\"purge_everything\":true}"
For Windows:
Replace the single quotes with double quotes: ' --> "
Escape the double quotes with a backslash: " --> \"
cmd.exe doesn't support single quotes, to run those commands straight from the docs you can use Bash.
Bash can be enabled in Windows 10 : https://www.laptopmag.com/uk/articles/use-bash-shell-windows-10
or Git Bash comes with Git for windows: https://gitforwindows.org/

How to echo variable inside single quotes using Bash?

users.I want to run a curl command with a bash script.
(below command works perfectly in terminal)
curl -i -H "Content-Type: application/json" -X POST -d '{"mountpoint":"/gua-la-autentica-1426251559"}' http://127.0.0.1:5000/connect
But unable to run this command in bash. When mountpoint value is given in a variable($final).
final="/gua-la-autentica-1426251559"
curl -i -H "Content-Type: application/json" -X POST -d '{"mountpoint":'$final'}' http://127.0.0.1:5000/connect
Could someone please help me, how to echo variable inside single quotes?
JSON string values should be quoted and so should parameter expansions. You can achieve this by using double quotes around the entire JSON string and escaping the inner double quotes, like this:
curl -i -H "Content-Type: application/json" -X POST -d "{\"mountpoint\":\"$final\"}" http://127.0.0.1:5000/connect
As mentioned in the comments, a more robust approach would be to use a tool such as jq to generate the JSON:
json=$(jq -n --arg final "$final" '{ mountpoint: $final }')
curl -i -H "Content-Type: application/json" -X POST -d "$json" http://127.0.0.1:5000/connect
I'd probably do it with a printf format. It makes it easier to see formatting errors, and gives you better control over your output:
final="/gua-la-autentica-1426251559"
fmt='{"mountpoint":"%s"}'
curl -i -H "Content-Type: application/json" -X POST \
-d "$(printf "$fmt" "$final")" \
http://127.0.0.1:5000/connect
I don't know where you're getting $final in your actual use case, but you might also want to consider checking it for content that would break your JSON. For example:
Portable version:
if expr "$final" : '[A-Za-z0-9./]*$'; then
curl ...
else
echo "ERROR"
fi
Bash-only version (perhaps better performance but less portable):
if [[ "$final" ]~ ^[A-Za-z0-9./]*$ ]]; then
curl ...
...
Checking your input is important if there's even the remote possibility that your $final variable will be something other than what you're expecting. You don't have valid JSON anymore if it somehow includes a double quote.
Salt to taste.

CouchDB cURL Windows Command Line Invalid JSON

Running the following command from a Windows command line using cURL attempting to post a new document to an existing CouchDB database (named test) fails:
curl -H "Content-Type: application/json" -X POST "http://127.0.0.1:5984/test" -d {"valid":"json"}
It returns the error:
{"error":"bad_request","reason":"invalid_json"}
The JSON is valid so what gives?
The answer is related to the formatting of the JSON string on the command line. Even though it is proper JSON when you type it, the command line, it seems, must reformat it before sending it.(Maybe someone else can explain why it does this in more detail.) To fix this you need to escape your quotations in the command line like so:
curl -H "Content-Type: application/json" -X POST "http://127.0.0.1:5984/test" -d {"""valid""":"""json"""}
See the extra quotation marks? This should work and return "ok:true" with an id and revision number.
You have to quote also the whole statement to support spaces like: -d "{\"title\":\"There is Nothing Left to Lose\" , \"artist\":\"Foo Fighters\"}"