How to use Bash command line to curl an API with token and payload as parameters - bash

I am novice and first timer to bash. Trying to run bash under command line to invoke an API, by passing token and payload received from two different APIs and are set as parameters. Below is my command. I am trying to add this bash script to a task in AzureBatch service job.
It has 3 curl requests,
First one (Line#1 in the code snippet below)- gets payload by
calling an API. ---- This is working fine, I am able to verify the
payload using the echo statement following the first curl command.
Second one(Line#3 in the code snippet below) - gets token by
calling the token provider ----- This is working fine as well,
verified using the echo statement.
Third one (Line#5 in the code snippet below),This is the problematic command. I am trying to pass the token and payload received from the above two commands and the curl is not able to resolve them.
both token and payload or not resolving to their values..
My Bash COmmand
/bin/bash -c
"payload=$(curl --location --request GET 'http://url/OutreachData')
&& echo -e \"The value of payload is: "'$payload'"\"
&& token=$(curl --location --request POST 'https://login.microsoftonline.com/<<tenantId>>/oauth2/v2.0/token' --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'client_id=<<clientId>>' --data-urlencode 'scope=api://<<applicationId>>/.default' --data-urlencode 'client_secret=<<clientSecret>>' --data-urlencode 'grant_type=client_credentials' --data-urlencode 'Audience=api://<<applicationId>>'|jq -j '.access_token')
&& echo -e \"value of token is "'$token'"\n\"
&& result=$(curl --location --request POST 'https://url/api/<<Resource>>' --header 'accept: */*' --header 'Content-Type: application/json' --header 'Authorization: Bearer '"'$token'" --data-raw "'$payload'")
&& echo -e \"Result is "'$result'"\""
This is how the third Curl is resolving to, payload and token are not getting replaced as we can see in the authorization header and data-raw elements
++ curl --location --request POST https://url/api/ --header 'accept: /' --header 'Content-Type: application/json' --header 'Authorization: Bearer ' --data-raw ''''''''

There should be no need to explicitly run this with bash -c unless you are in a very constrained environment where you simply cannot run Bash by any other means.
The immediate problem is that code like
bash -c "echo "'$token'" && true"
ends up with $token being single-quoted in the shell which you run bash -c from. But the blazingly obvious fix is to not have this complex quoting in the first place.
payload=$(curl --location --request GET 'http://url/OutreachData')
echo "The value of payload is: '$payload'"
token=$(curl --location --request POST \
'https://login.microsoftonline.com/<<tenantId>>/oauth2/v2.0/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=<<clientId>>' \
--data-urlencode 'scope=api://<<applicationId>>/.default' \
--data-urlencode 'client_secret=<<clientSecret>>' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'Audience=api://<<applicationId>>' |
jq -j '.access_token')
echo "value of token is "'$token'"
result=$(curl --location --request POST \
'https://url/api/<<Resource>>' --header 'accept: */*' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer '"$token" \
--data-raw "$payload")
echo "Result is "'$result'"
If your current shell is not Bash and you need these commands to be run in Bash, a simpler workaround is to put the script in a here document, which drastically simplifies the quoting needs (or if this is in an interactive session, just run bash and run these commands at the interactive Bash prompt, then exit when you no longer want to be in Bash).

Related

How to write output of looped curl command to file

I want to run a curl command every few seconds on a loop and I want the output to be written to a file (appending not overwriting each time it runs). I have to also run it from the CLI
Curl command is like below
curl --location --request POST 'https://api.website.com/Auth/token'
--header 'Content-Type: application/x-www-form-urlencoded'
--header 'Cookie: blablabla'
--data-urlencode 'grant_type=password'
--data-urlencode 'username=username'
--data-urlencode 'password=password
I tried adding a while true; do sleep 2 && at the beginning and > file.txt to output at the end but its not working. I'm sure its probably simple but I'm not very good with bash so any help would be great
You can do this:
while :; do
curl --location --request POST 'https://api.website.com/Auth/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Cookie: blablabla' \
--data-urlencode 'grant_type=password' \
--data-urlencode 'username=username' \
--data-urlencode 'password=password'
sleep 2 || break
done >> file.txt

How to remove the double quotes of a variable in shell scripting

The API authentication is denied as the value of $login_token variable that I pass in the curl command is enclosed with double quotes during the execution.
Code
set -x
login_token="eUsadjb#dsi-0nknhsnc"
API_Response=$(curl -X POST --header 'Accept: application/json' --header 'Authorization: Bearer '$login_token 'https://example.com')
set +x
Curl Response in Debug Mode
++ curl -X POST --header 'Content-Type: multipart/form-data' --header 'Accept: application/json' --header 'Authorization: Bearer "eUsadjb#dsi-0nknhsnc"'
+API_Response='Authorization has been denied for this request. Please use a valid access token.'
As you can notice that the login_token value is embedded with double quotes when passed as a variable and this causes the failure. The value of login_token variable should be passed without quotes as it is. Suppose, if I pass the value of login_token directly in the curl command, then the authentication is successful.
Direct Value - Authentication Success
API_Response=$(curl -X POST --header 'Accept: application/json' --header 'Authorization: Bearer eUsadjb#dsi-0nknhsnc' 'https://example.com')
How can I pass the value of login_token variable without quotes in curl command?
FYI, I tried the following method as well, but it doesn't work
login_token="eUsadjb#dsi-0nknhsnc"
API_Response=$(curl -X POST --header "Accept: application/json" --header "Authorization: Bearer $login_token" "https://example.com")

How can I set the environment variable in request header for curl?

How can I set the environment variable in request header for curl
curl --location --request POST 'test.example.com' \
--header 'Content-Type: application/json' \
--header 'access_token: "${SOME_ENV_TOKEN}"' \
--header 'Authorization: Basic Og=='
Not working.
Use --header "access_token: \"${SOME_ENV_TOKEN}\""
The ' quotes disable variable expansion in sh.

Get curl http code

I have the following cURL request. I want to get the http_code, but I want in a different variable, because otherwise it messes with parsing the JSON response from the GET call.
Is there anyway to do this?
curl --write-out %{http_code} --silent --output GET --header "Accept: application/json" --header "URL"
Just use command substitution to store status code in a variable:
status=$(curl --write-out %{http_code} --silent --output tmp.out GET --header "Accept: application/json" --header "URL")
data=$(<tmp.out)
# check status now
declare -p status
# check data
declare -p data
curl -i -H "Accept: application/json" "server:5050/a/c/getName{"param0":"Arvind "}"
curl -w 'RESP_CODE:%{response_code}' -s -X POST --data '{"asda":"asd"}' http://example.com --header "Content-Type:application/json"|grep -o 'RESP_CODE:[1-4][0-9][0-9]'
response=$(curl -sb -H "Accept: application/json" "http://host:8080/some/resource") For response just try $response
Try this following may be this could help you to find the solution https://gist.github.com/sgykfjsm/1dd9a8eee1f70a7068c9

bash encapsulate command options in variables

I have a bunch of these to test my RESTful API
$CURL \
-v \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-X POST \
-d '{"user":{"email":"user#example.com","password":"secret"}}' \
$URL/$PATH/sessions
I kinda want to shorten it to something like
CURLOPTS="-v -H 'Content-Type: application/json' -H 'Accept: application/json'"
$CURL \
$CURLOPTS \
-X POST \
-d '{"user":{"email":"user#example.com","password":"secret"}}' \
$URL/$PATH/sessions
but the options don't seem to be passed in. Any clues?
Short answer: see BashFAQ #50:'m trying to put a command in a variable, but the complex cases always fail!.
Long answer: Putting commands (or parts of commands) into variables and then getting them back out intact is complicated. The reason your script doesn't work is because of the order in which the shell parses the command line: it parses (and removes) quotes and escapes, then replaces variable values. By the time $CURLOPTS gets replaced, it's too late for the quotes to have their intended effect; instead, they're passed to curl as part of the arguments, which confuses curl greatly.
The solution: store the options in an array rather than a plain string:
CURLOPTS=(-v -H 'Content-Type: application/json' -H 'Accept: application/json')
$CURL \
"${CURLOPTS[#]}" \
-X POST \
-d '{"user":{"email":"user#example.com","password":"secret"}}' \
"$URL/$PATH/sessions"
You can use an array and trigger word splitting
$ set -x
$ CURLOPTS=(-v -H 'Content-Type: application/json' -H 'Accept: application/json')
$ : curl "${CURLOPTS[#]}"
+ : curl -v -H 'Content-Type: application/json' -H 'Accept: application/json'

Resources