Convert Powershell command to curl - powershell

I am trying make the following API calls with a curl command and run it on Linux:
https://octopus.com/blog/manually-push-build-information-to-octopus
This what I got:
curl -X POST https://YourServerUrl -H "X-Octopus-ApiKey"="API-XXXXXXXXXXXXXXXXXXXXXXXXXX" -H "Content-Type: application/json" -d "#jsonBody"
I am not sure how to convert this script to a json in curl
$jsonBody = #{
PackageId = "twerthi/xCertificatePermission"
Version = "1.0.0"
OctopusBuildInformation =
#{
BuildEnvironment = "Jenkins"
VcsCommitNumber = "2350881a389517288b31432d469c5c4199a1fba9"
VcsType = "Git"
VcsRoot = "https://github.com/twerthi/xCertificatePermission.git"
}
} | ConvertTo-Json -Depth 10

The curl command -d (--data) is the specified data in the POST request. So you should be able to just enter valid JSON data as part of the call. i.e. something like this:
curl -X POST https://YourServerUrl -H "X-Octopus-ApiKey"="API-XXX" -H "Content-Type: application/json" -d '{ "PackageId":"twerthi/xCertificatePermission", "Version":"1.0.0", "OctopusBuildInformation":{ "BuildEnvironment":"Jenkins", "VcsCommitNumber":"2350881a389517288b31432d469c5c4199a1fba9", "VcsType":"Git", "VcsRoot":"https://github.com/twerthi/xCertificatePermission.git"}}'
Note, if you are testing this in cmd/bash etc, you can split the command over multiple lines by using an escape character. Windows: ^ Linux/MacOS: \
Example in Windows:
curl -X POST https://YourServerUrl ^
-H "X-Octopus-ApiKey"="API-XXX" ^
etc....
Also, assuming that's valid PS, you can just run it and check the result in $jsonBody to see how its formatted.

Assuming you want to call the external curl utility from PowerShell (note that on Windows, in Windows PowerShell, you'll have to call it as curl.exe):
curl -X POST https://YourServerUrl `
-H 'X-Octopus-ApiKey: API-XXXXXXXXXXXXXXXXXXXXXXXXXX' `
-H 'Content-Type: application/json' `
-d ($jsonBody -replace '([\\]*)"', '$1$1\"')
Note the unfortunate need for a -replace operation on the $jsonBody variable containing your JSON string, which - as of PowerShell 7.1 - is needed to work around a long-standing bug, discussed in this answer.

Related

Unable to use curl with double quote using powershell (Hubspot API)

I use Hubspot API.
I try to craete contact info.
Type this code using powershell (5.1version and 7.2)
curl.exe --request POST --url "https://api.hubapi.com/crm/v3/objects/contacts?hapikey=$apiKey"
--header 'content-type: application/json' -d "{\"properties\": {\"email\":\"$email\",\"firstname\":\"$firstname\"}}"
but error
return {"status":"error","message":"Invalid input JSON on line 1, column 3: Unexpected character ('\\' (code 92)): was expecting double-quote to start field name","correlationId":"2086b3bc-abe5-4f90-a79c-213d45bb2a97"}
I try this code using single quote after -d.
and then create contact info.
curl.exe --request POST --url "https://api.hubapi.com/crm/v3/objects/contacts?hapikey=$apiKey" --header 'content-type: application/json' -d '{\"properties\": {\"email\":\"xxx#yyy.co.jp\",\"firstname\":\"k\"}}'
but I want to substitute variables. So I want to use double quote.
I solved by myself.
put double-quotes and backslash between variable.
ConvertTo-Json
setting 2. to curl.exe
like this
$contactBody = #{
'"properties"' = #{
'"firstname"' = "`"$firstname`""
'"email"' = "`"$email`""
}
}
$contactBodyJson = ConvertTo-Json $contactBody
curl.exe --request POST --url "https://api.hubapi.com/crm/v3/objects/contacts?hapikey=$apiKey" --header 'content-type: application/json' -d $contactBodyJson

Remote server Run CMD in Powershell

I am trying to upload a Zip file via RestAPI in powershell and Powershell version I am using is 5.1.
since Invoke-restmethod in powershell 5.1 doesn't have -form option,I tried to run curl command in CMD using powershell.When I run it locally it's working correctly. But when i try to run it in a server(azure devops agent) I am getting error saying curl command is not recognized.
What am i missing here it's runs as expected when i try in vs code, but not when i run it from a server.
$header1 = "accept: application/json"
$header2 = "X-Authorization: $($token)"
$header3 = "Content-Type: multipart/form-data"
$body1 = "upload=#Name.zip;type=application/x-zip-compressed"
$body2 = "actionIfExisting=Existing"
$body3 = "publicWorkspace=Public"
cmd.exe /c curl -X POST $uri -H $header1 -H $header2 -H $header3 -F $body1 -F $body2 -F $body3
Luckily I had git installed in the server and I read in this stack overflow page that Git comes with preInstalled curl.exe. So I called the path where git has curl.exe and using & operator in powershell to execute the curl.exe directly in powershell itself.
& 'C:\users\git\mingw64\bin\curl.exe' -X POST $uri -H $header1 -H $header2 -H $header3 -F $body1 -F $body2 -F $body3

Calling REST API with special characters in data parameters from Perl is failing

From perl i'm trying to call a servicenow rest api to update some data attributes.
I'm using curl command to achieve this and for some reasons i can't use any of the perl modules available.
I'm able to achieve this successfully without any special characters in the value field of the json.
Following is the code used for formatting the cmd:
my $comments = "b'c";
my $cmd = `curl \"$url\" -i -s --insecure --user test:test --request PUT --header "Accept:application/json" --header "Content-Type:application/json" --data '{\"comments\":\"$comments\"}'`;
If the above value is "bc" i'm able to get the data, but if i give "b'c" the i'm getting following errors:
sh: -c: line 0: unexpected EOF while looking for matching `"'
sh: -c: line 1: syntax error: unexpected end of file
Even i tried the following code:
my $cmd = system "curl https://test.service-now.com/api/now/table/incident/code?sysparm_display_value=true -i -s --insecure --request PUT --header \"Accept:application/json\" --header \"Content-Type:application/json\" --data '{\"comments\":\"bc\"}' --user test:test";
If a string with single quote b'c is given I'm getting the same error.
Could somebody please tell me how to handle single quote inside double quoted string?
I can get this working with
my $comments = "b\"'\"c";
The string that gets passed to the shell is then
--data '{"comments":"b'"'"'c"}'
which is three separate tokens concatenated together:
'{"comments":"b' resolves to {"comments":"b
"'" resolves to '
'c"}' resolves to c"}
Also see String::ShellQuote, which is a godsend for problems like this.
use String::ShellQuote;
$comments = "b'c";
#cmd = ("curl", $URL, "-i", "-s", "--insecure", "--request",
"PUT", "--header", "Accept:applicatin/json", "--header",
"Content-Type:application/json",
"--data", qq[{"comments":$comments}], "--user", "test:test");
$cmd = shell_quote(#cmd);
print $cmd;
Gives you:
curl 'https://test.service-now.com/api/now/table/incident/code?sysparm_display_value=true'
-i -s --insecure --request PUT --header
Accept:application/json --header Content-Type:application/json
--data '{"comments":"b'\''c"}' --user test:test
which would also satisfy the shell's syntax checker.

Calling an PingAccess APIs from Powershell

I am trying to call PingAccess APIs to configure my PingAccess.
I am new to using APIs to do this, and have a question.
I am trying to use CURL to the API .
curl -k -u Administrator:dummypsswd -H "X-Xsrf-Header: PingAccess" -H "Content-Type: application/json" -d '{"alias":"PLACEHOLDER_STAR_MINGLE","fileData": [[System.IO.File]::ReadAllBytes("C:\test.pfx")],"password": "1234"}' https://localhost:9000/pa-admin-api/v1/keyPairs/import -v
When I run this I get the following error.
I still dont know why am I unauthorized. Any help is appreciated.
When you have special characters in your password you'll need to enclose the username/password tuple in double quotes:
curl -k -u "Administrator:dummypsswdwithspecialcharslike&&" -H "X-Xsrf-Header: PingAccess" -H "Content-Type: application/json" -d '{"alias":"PLACEHOLDER_STAR_MINGLE","fileData": [[System.IO.File]::ReadAllBytes("C:\test.pfx")],"password": "1234"}' https://localhost:9000/pa-admin-api/v1/keyPairs/import -v

Curl thowing error while trying to query JIRA with strings in field filter

I need some help with my perl script.
I am new to perl and using curl and despite a lot of searching/ trial and error I am still stumped.
I am trying to use CURL to retrieve a set of jira issues based on the provided JQL.
Unfortunately I am having issues with spaces when I search fields like summary:
my $jql = JiraUrl.'search?jql=summary~"Some%20Silly%20Issue"';
When I curl this...
my $jsonResponse = `curl -D- -u $user:$password -X GET -H "Content-Type: application/json" $jql`;
I get an error ..
{"errorMessages":["Error in the JQL Query: Expecting either \'OR\' or \'AND\' but got \'Silly\'. (line 1, character 77)"],"errors":{}}';
Basicly when I escape the " " with %20 it ignores the "'s
Any help for how to get around this?
It looks like it's a shell escaping issue. The quotes are being interpreted by the shell. Try this:
my $jsonResponse = `curl -D- -u $user:$password -X GET -H "Content-Type: application/json" '$jql'`;