Batch curl -d from JSON file - json

I have a JSON file and I would like to pass each object to a curl -d command :
[
{
"number":"+336770002979",
"message":"La plupart\ntest",
"sender":"BEcompany",
"date": 1539286620000
},
{
"number":"+336600000780",
"message":"La plupart\ntest",
"sender":"BEcompany",
"date": 1539286620000
},
...
]
For now I tried this
curl -X POST \
-H "X-Primotexto-ApiKey: 784155eed9d0a4d1ffdb67466" \
-H "Content-Type: application/json" \
-d #json.json \
https://api.primotexto.com/v2/notification/messages/send;
but it only reads the first object.
Edit
I fixed the [...] in the JSON and the curl command based on the comments.

You can use jq -c .[] to split the file to one array element per line, and take it from there.
jq -c .[] json.json |
while IFS= read -r fragment; do
curl -options -etc -d "$fragment" "http://url"
done

Related

Trying to include a dynamic variable within JSON data of a Bash / Shell POST request to API endpoint

I am trying to submit a POST request using Bash that includes JSON data with a variable equal to that of a random string. I get the string dynamically by parsing a file which can vary in content... and may contain regex characters and also new lines.
I will provide an example string here with a curl request that works successfully with the API I am posting this request to. I can only get the request to go through with the string hardcoded into the JSON data and not while assigning a variable to the string like for instance stringVar and using the variable in the JSON data. I could sure use some help where I am messing this up
my working shell script looks something like this
#!/bin/bash
curl -i -H "Authorization: Bearer <MY_API_TOKEN>" -H "Content-Type: application/json" -H "Accept: application/json" -X POST 'https://api.example.com/v1/endpoint' -d '{
"name": "my-project",
"files": [
{
"data": "helloWorldFunction() {\n echo \"hello world\" \n}"
},
],
}'
This works, however I need to change data's value from the string
helloWorldFunction() {\n echo "hello world" \n}
to a variable
I have tried settings the variable in different ways in the JSON content from reading suggestions on other questions. For instance I have tried tried changing my shell script to
#!/bin/bash
stringVar="helloWorldFunction() {\n echo \"hello world\" \n}"
curl -i -H "Authorization: Bearer <MY_API_TOKEN>" -H "Content-Type: application/json" -H "Accept: application/json" -X POST 'https://api.example.com/v1/endpoint' -d '{
"name": "my-project",
"files": [
{
"data": "${stringVar}"
},
],
}'
i have tried setting the variable like this
"${stringVar}" | turns into ${stringVar}
"$stringVar" | turns into "$stringVar"
and
"'${stringVar}'"
"'$stringVar'"
both seem to return this error
{"error":{"code":"bad_request","message":"Invalid JSON"}}curl: (3) unmatched brace in URL position 1: {\n
and
stringVar
stringVar
$stringVar
"'"$stringVar"'"
""$stringVar""
${stringVar}
all seem to return this error
{"error":{"code":"bad_request","message":"Invalid JSON"}}
Ahh any help on what I am doing wrong would be great.
Thanks in advance y'all
In order to interpolate the value of a variable, you need to enclose the string in double-quotes("), but the JSON also requires literal double-quotes.
The easiest solution is probably to use a here-document to feed the data into curl's standard input, as in #Gilles Quénot's answer. But you can still pass it in via the command line; you just have to be careful with the quotes.
This is one way:
curl ... -d '{
"name": "my-project",
"files": [
{
"data": "'"$stringVar"'"
}
]
}'
The JSON here is mostly contained within single quotation marks ('...'). But right after opening the pair of literal "s that will enclose the value of data, we close the single quotes and switch our shell quotation mode to double quotes in order to include the value of $stringVar. After closing the double quotes around that expansion, we go back into single quotes for the rest of the JSON, starting with closing the literal double-quotes around the value of data.
In a language that used + for string concatenation, it would look like '... "data": "' + "$stringVar" + '"... ', but in the shell you just put the strings next to each other with no operator to concatenate them.
As an alternative, you could put the whole thing in double-quotes, but then you need backslashes to include the literal double quotes that are part of the JSON:
curl ... -d "{
\"name\": \"my-project\",
\"files\": [
{
\"data\": \"$stringVar\"
}
]
}"
So that requires a lot more changes if you're starting from plain JSON; it also looks messier, IMO.
You can also use a tool that knows how to build JSON and let it worry about quoting etc. Here's one way to build it with jq:
jq -n --arg data "$stringVar" '{
"name": "my-project",
"files": [
{
"data": $data
}
]
}'
Using --arg creates a variable inside jq – I named it data – which can then be included in an expression with the syntax $varname ($data in this case). Despite the similarity of syntax, that's not a shell interpolation; we're passing the literal text $data to jq, and jq itself is what replaces it with the value of the variable (which was passed as the second argument to --arg).
There's another tool called jo, which doesn't manipulate JSON but rather produces it, from input that is easier to generate in the shell. Here's one way to construct the desired object with it:
jo name=my-project files="$(jo -a "$(jo data="$stringVar")")"
Either way you can include the constructed JSON in your curl command line like this:
curl ... -d "$(jo or jq command goes here)"
Do not generate such JSON by hand. Use a tool like jq to do it for you.
#!/bin/bash
stringVar="helloWorldFunction() {\n echo \"hello world\" \n}"
jq -n --arg s "$stringVar" '{name: "my-project", files: [{data: $s}]}' |
curl -i -H "Authorization: Bearer <MY_API_TOKEN>" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-X POST \
-d #- \
'https://api.example.com/v1/endpoint'
Like this:
#!/bin/bash
stringVar="..."
curl -i -H "Authorization: Bearer <MY_API_TOKEN>" \
-H "Content-Type: application/json" \
-H "Accept: application/json" -X POST 'https://api.example.com/v1/endpoint' \
-d#/dev/stdin <<EOF
{
"name": "my-project",
"files": [
{
"data": $stringVar
},
],
}
EOF
You then should take care about what you fed in the variable, this have to be valid JSON
As an alternative to jq and curl you could use xidel to generate the JSON and submit the POST-request.
With command-line options:
#!/bin/bash
stringVar='helloWorldFunction() {\n echo "hello world" \n}'
xidel -s --variable var="$stringVar" \
-H "Authorization: Bearer <MY_API_TOKEN>" \
-H "Content-Type: application/json" \
-H "Accept: application/json"
-d '{serialize(
{"name":"my-project","files":array{{"data":$var}}},
{"method":"json"}
)}' \
"https://api.example.com/v1/endpoint" \
-e '$raw'
Or with the x:request() function in-query:
#!/bin/bash
stringVar='helloWorldFunction() {\n echo "hello world" \n}'
xidel -s --variable var="$stringVar" -e '
x:request({
"headers":(
"Authorization: Bearer <MY_API_TOKEN>",
"Content-Type: application/json",
"Accept: application/json"
),
"post":serialize(
{"name":"my-project","files":array{{"data":$var}}},
{"method":"json"}
),
"url":"https://api.example.com/v1/endpoint"
})/raw
'
$raw / /raw returns the raw output, like curl. If the API-endpoint returns JSON, then you can use $json / /json to parse it.

Convert log files to base64 and upload it using Curl to Github

I am trying to upload a file to Github using its API.
Following code works, but only with smaller size content which is approx less than 1MB.
tar -czvf logs.tar.gz a.log b.log
base64_logs=$(base64 logs.tar.gz | tr -d \\n)
content_response=$(curl \
-X PUT \
-u :"$GIT_TOKEN" \
-H "Accept: application/vnd.github.v3+json" \
"$content_url" \
-d '{"message": "Log files", "content": "'"$base64_logs"'"}')
For content that is a bit large, I get the following error:
/usr/bin/curl: Argument list too long
Now, there is already a question on SO about this error message, and it says that to upload a file directly. See here: curl: argument list too long
When I try this, I get a problem parsing JSON error message.
tar -czvf logs.tar.gz a.log b.log
base64_logs=$( base64 logs.tar.gz | tr -d \\ ) > base64_logs.txt
content_response=$(curl \
-X PUT \
-u :"$GIT_TOKEN" \
-H "Accept: application/vnd.github.v3+json" \
"$content_url" \
-d '{"message": "Log files", "content": #base64_logs.txt}')
Can anyone point me out where I am making mistake here? Thanks!
Use the base64 command rather than the #base64 filter from jq, because the later can only encode textual data and not binary data as from a .gz archive.
Pipe the base64 stream to jq to format it into a JSON data stream.
Curl will read the JSON data stream and send it.
# use base64 to encode binary data and -w0 all in one-line stream
base64 --wrap=0 logs.tar.gz |
# JSON format from raw input
jq \
--raw-input \
--compact-output \
'{"message": "Log files", "content": . }' |
# Pipe JSON to curl
curl \
--request PUT \
--user ":$GIT_TOKEN" \
--header "Accept: application/vnd.github.v3+json" \
--header 'Content-Type: application/json' \
--data-binary #- \
--url "$content_url"

Interpolate command output into GitHub REST request

I am trying to create a pull request comment automatically whenever CI is run. The output of a given command is written to a file (could also just be stored inside an environment variable though). The problem is, I usually get the following response:
curl -XPOST -d "{'body':'$RESULT'}" https://api.github.com/repo/name/issues/number/comment
{
"message": "Problems parsing JSON",
"documentation_url": "https://developer.github.com/v3/issues/comments/#create-a-comment"
}
This is usually due to unescpaed characters, like \n, \t, " etc.
Is there any easy way to achieve this on the command line or in bash, sh, with jq or Python? Using the Octokit.rb library is works straight away, but I don't want to install Ruby in the build environment.
You can use jq to create your JSON object. Supposing you have your comment content in RESULT variable, the full request would be :
DATA=$(echo '{}' | jq --arg val "$RESULT" '.| {"body": $val}')
curl -s -H 'Content-Type: application/json' \
-H 'Authorization: token YOUR_TOKEN' \
-d "$DATA" \
"https://api.github.com/repos/:owner/:repo/issues/:number/comments"
The post "Using curl POST with variables defined in bash script functions" proposes multiple techniques for passing a varialbe like $RESULT in a curl POST parameter.
generate_post_data()
{
cat <<EOF
{
"body": "$RESULT"
}
EOF
}
Then, following "A curl tutorial using GitHub's API ":
curl -X POST \
-H "authToken: <yourToken" \
-H "Content-Type: application/json" \
--data "$(generate_post_data)" https://api.github.com/repo/name/issues/number/comment

Include command output to json

Trying to send a weekly overview of the backup size from a bash script which does a curl to send a message.
echo $(curl -s \
-X POST \
--user "aasdfasdfbc:4adgadfgsdfg" \
https://api.mailjet.com/v3/send \
-H "Content-Type: application/json" \
-d '{
"FromEmail":"noreply#bashdrsh.li",
"FromName":"Backup Notification",
"Recipients": [
{
"Email":"back.upper#bashdrsh.li"
}
],
"Subject":"['"$host"'] Backup overview",
"Text-part":"Backup on '"$host"' weekly overview\n\n '"$(find /tmp/backup/2017-07-12/ -maxdepth 1 -type f -exec ls -hls {} \; | awk '{ printf "%-40s %30s\n", $10, $6 }')"'\n"
}')
But the find command always returns with this response
find: paths must precede expression: globals-only.7z
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec|time] [path...] [expression]
{
"FromEmail":"noreply#bashdrsh.li",
"FromName":"Backup Notification",
"Recipients": [
{
"Email":"back.upper#bashdrsh.li"
}
],
"Subject":"[MYLOCAL] Backup overview",
"Text-part":"Backup on MYLOCAL weekly overview\n\n \n"
}
Running the find command on command line it returns everything as expected
# find /tmp/backup/2017-07-12/ -name '*.7z' -exec ls -hls {} \; | awk '{ printf "%-40s %30s\n", $10, $6 }'
/tmp/backup/2017-07-12/globals-only.7z 7.3K
/tmp/backup/2017-07-12/auth.7z 759
How can I include a nice formatted table into the message?
You're not using the same find expression in curl invocation and later on command line. Also, no need for ls & awk.
Try replacing your complete command substitution with:
find /tmp/backup/2017-07-12/ -name '*.7z' -printf "%-40P %30s\n"
For readability, you can store that into a variable, and use like:
output=$(find /tmp/backup/2017-07-12/ -name '*.7z' -printf "%-40P %30s\n")
echo $(curl -s \
-X POST \
--user "aasdfasdfbc:4adgadfgsdfg" \
https://api.mailjet.com/v3/send \
-H "Content-Type: application/json" \
-d '{
"FromEmail":"noreply#bashdrsh.li",
"FromName":"Backup Notification",
"Recipients": [
{
"Email":"back.upper#bashdrsh.li"
}
],
"Subject":"['"$host"'] Backup overview",
"Text-part":"Backup on '"$host"' weekly overview\n\n '"$output"'\n"
}')

Passing a shell variable to a JSON request to curl?

Let's take the following example:
curl -i -X POST \
-H "Content-Type: application/json" \
-d '{"jsonrpc": "2.0", "method": "Player.Open", "params":{"item":false}}' \
http://example.com/jsonrpc
Now I want to have the boolean value of "item" be set in a shell script variable such as:
PRIVATE=false
read -p "Is this a private? (y/[n]) " -n 1 -r
if [[ $REPLY =~ ^[Yy]$ ]]; then
PRIVATE=true
fi
And I want to pass in the value of PRIVATE to item. I have tried every which way but no luck. Can anyone shed some light?
You can do it this way:
curl -i -X POST \
-H "Content-Type: application/json" \
-d '{"jsonrpc": "2.0", "method": "Player.Open", "params":{"item":'"$PRIVATE"'}}' \
http://example.com/jsonrpc
Instead of your existing -d ... line above, you could try the following:
-d "{\"jsonrpc\": \"2.0\", \"method\": \"Player.Open\", \"params\":{\"item\":$PRIVATE}}" \
That is: when using double quote speechmarks ("), bash substitutes values for variables referenced $LIKE_THIS (not the case for single quotes you were using). The downside is that you then need to escape any double-quotes in the string itself (using the backslash, as above).
This abomination works too.
$ npm run script -- madrid
# script
json='{"city":"'"$1"'"}'
curl -X POST -d $json http://localhost:5678/api/v1/weather