POST request with Powershell 2.0 using cURL - rest

Scenario
Among other things, Powershell 2.0 doesn't have the useful cmdlet Invoke-RestMethod.
I can't upgrade to version 3 and most examples I've found use version 3.
I have found this article, which seems, however, too complicated for my simple scenario.
I need to write a Powershell script that POSTs data in Json format, e.g.
{"Id":5,"Email":"test#com","DataFields":null,"Status":0}
What I've tried
I am able to GET data. This is one of the scripts I have tried.
curl -v --user username:password https://api.dotmailer.com/v2/account-info
But, when I try to POST, I can't figure out where to put the body of the message in the script. This is what I've got so far:
curl -v -X POST -H "Accept: application/json" -H "Content-Type: application/json" -u username:password -d '{"Id":5,"Email":"test#com","OptInType":0,"EmailType":0, "DataFields":null,"Status":0}' https://api.dotmailer.com/v2/contacts
which returns the following error:
{"message":"Could not parse the body of the request based on the content type \"application/json\" ERROR_BODY_DOES_NOT_MATCH_CONTENT_TYPE"}*
Question
Can anyone advise on how to POST Json data from Powershell using cURL?
Any pointers to why I get the error I mentioned in the Waht I've tried section would be much appreciated.
Thanks.

Note that the question is about the curl.exe external program, not about PowerShell's Invoke-WebRequest cmdlet (which, unfortunately, is aliased to curl in later PowerShell versions, preempting calls to the external program unless the .exe extension is explicitly specified (curl.exe ...).
Unfortunately and unexpectedly, you have to \-escape embedded " instances in a string you pass as an argument to an external program.
Therefore, even though:
'{"Id":5,"Email":"test#com","DataFields":null,"Status":0}'
should work, it doesn't, due to a long-standing bug; instead, you must use:
'{\"Id\":5,\"Email\":\"test#com\",\"DataFields\":null,\"Status\":0}'
See this answer for more information.

From curl's man page it appears you need to use -d switch:
curl -v --user username:password -H "Content-Type: application/json" -d '{"Id":5,"Email":"test#com","DataFields":null,"Status":0}' https://api.dotmailer.com/v2/contacts

Related

Add existing user to existing group apache ranger

im looking at apache Ranger rest API to add an existing internal user/users to an existing internal group.
I have been looking at the docs and cant seem to find something useful,is there an API for that?
Try following api call:-
curl -ivk -u admin:admin -H "Content-Type: application/json" -d '{"id":13,"createDate":"2020-12-23T07:55:04Z","updateDate":"2020-12-23T07:55:04Z","owner":"rangerusersync","updatedBy":"rangerusersync","name":"atlas","password":"*****","description":"atlas - add from Unix box","groupIdList":[6,59,4,131,133],"groupNameList":["atlas","hadoop","shadow"],"status":0,"isVisible":1,"userSource":1,"userRoleList":["ROLE_USER"],"otherAttributes":"{\"full_name\":\"atlas\",\"original_name\":\"atlas\"}"}' -X PUT https://RANGER_HOST:6182/service/xusers/users
Its little bit big but if user is already added to ranger then run following api to get the id information for users:-
curl -ivk -u admin:admin -H "Accept : application/json" -X GET https://RANGER_HOST:6182/service/xusers/users
Once you have IDs for all users, you can run following curl api to get the json formatted data which you can use to modify and then use PUT method in first API I mentioned:-
curl -ivk -u admin:admin -H "Accept: application/json" -X GET https://RANGER_HOST:6182/service/xusers/users/13
Above Curl api should return something like following:-
{"id":13,"createDate":"2020-12-23T07:55:04Z","updateDate":"2020-12-23T16:45:14Z","owner":"rangerusersync","updatedBy":"admin","name":"atlas","password":"*****","description":"atlas - add from Unix box","groupIdList":[133,6],"groupNameList":["apitest","atlas","hadoop","shadow","ssb"],"status":0,"isVisible":1,"userSource":1,"userRoleList":["ROLE_USER"],"otherAttributes":"{\"full_name\":\"atlas\",\"original_name\":\"atlas\"}"}
you have to modify "groupIdList":[133,6] from the above output copy entire output and pass it with PUT method as shown in the first api call mentioned above.

Passing API key with HTTP header in cURL

I have an API Proxy in Apigee which is authenticated with an API key. I'm passing the key with my HTTP request header using cURL, with this command:
curl -v -H "apikey: my_key" http://api_org-test.apigee.net/v1/helloapikey
I get this error:
Invoke-WebRequest : Cannot bind parameter 'Headers'. Cannot convert the
"apikey: my_key" value of type "System.String" to
type "System.Collections.IDictionary".
When I modify my policy to look for the key in query parameter rather than the header, it works fine. Am I missing something here?
Try this:
curl -v -H #{'apikey' = 'my_key'} http://api_org-test.apigee.net/v1/helloapikey
Note:
curl is an alias for the Invoke-WebRequest cmdlet:
Get-Alias curl
output:
CommandType Name
----------- ----
Alias curl -> Invoke-WebRequest
You could install curl:
https://stackoverflow.com/a/16216825/3013633
Remove existing curl alias by executing this command:
Remove-item alias:curl
Then your command will work:
curl -v -H "apikey: my_key" http://api_org-test.apigee.net/v1/helloapikey
None of the above answers worked for me (I got an error -- parse error near }).
This worked:
curl -X GET \
'http://api_org-test.apigee.net/v1/helloapikey' \
-H 'apikey: my_key'
PowerShell simply does not resolve the variable within your URL. You are trying to query the service at the URI http://$serverHost:1234/service which won't work. You could do
$serverHost = "myHost"
$service = "http://$serverHost`:1234/service"
Invoke-WebRequest $service -Method Get
Just to add this to the discussion, I had to both hash the api key, but leave the token call key phrase rather than change it to 'apikey'. That's just what worked for me!
curl -v -H #{'X-API-TOKEN' = '[*insert key here*]'} '*datacenter_url*)'
Also noteworthy to PowerShell newcomers, -v stands for verbose. This switch gives you a Cyan-colored text under the command in PowerShell ise about the command PS is running. Almost like a play-by-play commentary. Useful enough I thought I'd mention it.

Mashape multipart-form POST request

I have a POST method in my API which uses multipart encoded form data. I have set up the correct header and data settings so that the mashape web interface generated the following curl:
curl -X POST --include 'https://sslavov-text-analytics-v1.p.mashape.com/news' \
-H 'Authorization: Basic ***********' \
-H 'X-Mashape-Key: ************' \
-H 'Content-Type: multipart/form-data' \
-F 'file=#sample.docx' \
-F 'meta={"documentType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"};type=application/json'
Basically i'm trying to upload a file with a simple paragraph of text for processing. The curious part is that when I run this exact curl in a bash script, everything works smoothly, but when I try to run it through mashape, it says either 400 Bad Request or 500 Internal Server Error
In my particular case, these errors are generated when I don't pass correct form or headers. So my question is: Is there an error in the curl syntax or should I keep looking for the error on server side?
EDIT: I figured out what the problem was. -F 'file=#sample.docx' was passed before -F 'meta....' and that was causing the 500 Internal Server Error So now the question is: Is there any way to specifically arrange the order of the form fields (because mashape rearranges them aplhabetically)?

Creating JIRA issue using curl from command line

I've been through documentation here according to which I'm creating a issue for JIRA . I know I'm making some terribly small mistake .
I'm trying to create a new JIRA request from command line (later I'll integrate in my java code)
From my Mac terminal I'm trying to run :
curl -D- -u username:password -X POST --data {"fields":{"project":{"key": “PROJECTKEY"},"summary": "REST ye merry gentlemen.","description": "Creating of an issue using project keys and issue type names using the REST API","issuetype": {"name": "Bug"}}} -H "Content-Type: application/json" https://mycompanyname.atlassian.net/rest/api/2/issue/
I believe this has something to do with the "data".
Thanks in advance. The example has been taken from the documentation link itself.
OUTPUT : I'm getting nothing in my terminal, no error, no expected output .
PROJECTKEY is taken from the KEY column from the All Project list in my DASHBOARD.
Two things are off:
you need to put the data that you want to post in quotes
the first double quote surrounding PROJECT_KEY is a unicode character instead of a regular double quote, so change “PROJECTKEY" to "PROJECTKEY"
This should work:
curl -D- -u username:password -X POST --data '{"fields":{"project":{"key": "PROJECTKEY"},"summary": "REST ye merry gentlemen.","description": "Creating of an issue using project keys and issue type names using the REST API","issuetype": {"name": "Bug"}}}' -H "Content-Type: application/json" https://mycompanyname.atlassian.net/rest/api/2/issue/

Create jobs and execute them in jenkins using REST

I am trying to create a WCF REST client that will communicate to Jenkins and create a job from an XML file and then build the job. My understanding is that you can do that with Jenkins.
Can some one please provide some commands that you can type on a browser's address bar to create and build jobs? ie: http:localhost/jenkins/createItem?name=TESTJOB something along those lines.
Usually, when parsing through the documentation, it can take one or two days. It is helpful to be able to access code or curl commands to get you up and running in one hour. That is my objective with a lot of third party software.
See the post at http://scottizu.wordpress.com/2014/04/30/getting-started-with-the-jenkins-api/ which lists several of the curl commands. You will have to replace my.jenkins.com (ie JENKINS_HOST) with the your own url.
To create a job, for instance, try:
curl -X POST -H "Content-Type:application/xml" -d "<project><builders/><publishers/><buildWrappers/></project>" "http://JENKINS_HOST/createItem?name=AA_TEST_JOB2"
This uses a generic config. You can also download a config from a manually created job and then use that as a template.
curl "http://JENKINS_HOST/job/MY_JOB_NAME/config.xml" > config.xml
curl -X POST -H "Content-Type:application/xml" -d #config.xml "http://JENKINS_HOST/createItem?name=AA_TEST_JOB3"
To execute the job (and set string parameters), use:
curl "http://JENKINS_HOST/job/MY_JOB_NAME/build"
curl "http://JENKINS_HOST/job/MY_JOB_NAME/buildWithParameters?PARAMETER0=VALUE0&PARAMETER1=VALUE1"
See the Jenkins API Wiki page (including the comments at the end). You can fill in the gaps using the documentation provided by Jenkins itself; for example, http://JENKINS_HOST/api will give you the URL for creating a job and http://JENKINS_HOST/job/JOBNAME/api will give you the URL to trigger a build.
I highly recommend avoiding the custom creation of job configuration XML files and looking at something like the Job DSL plugin instead. This gives you a nice Groovy-based DSL to create jobs programmatically - much more concise and less error-prone.
Thanks to a GIST - https://gist.github.com/stuart-warren/7786892
Check if job exists
curl -XGET 'http://jenkins/checkJobName?value=yourJobFolderName' --user user.name:YourAPIToken
With folder plugin
curl -s -XPOST 'http://jenkins/job/FolderName/createItem?name=yourJobName' --data-binary #config.xml -H "Content-Type:text/xml" --user user.name:YourAPIToken
Without folder plugin
curl -s -XPOST 'http://jenkins/createItem?name=yourJobName' --data-binary #config.xml -H "Content-Type:text/xml" --user user.name:YourAPIToken
Create folder
curl -XPOST 'http://jenkins/createItem?name=FolderName&mode=com.cloudbees.hudson.plugins.folder.Folder&from=&json=%7B%22name%22%3A%22FolderName%22%2C%22mode%22%3A%22com.cloudbees.hudson.plugins.folder.Folder%22%2C%22from%22%3A%22%22%2C%22Submit%22%3A%22OK%22%7D&Submit=OK' --user user.name:YourAPIToken -H "Content-Type:application/x-www-form-urlencoded"
If you want to create a job into a view given the view exists.
curl -X POST -H "Content-Type:application/xml" -d #build.xml "http://jenkins_host/view/viewName/createItem?name=itemName"
the build.xml filetemplate could be found in the root directory of a job's workspace
if you want to create a view:
curl -X POST -H "Content-Type:application/xml" -d #view.xml "http://jenkins_host/createView?name=viewName"
the content of the file view.xml could be:
<?xml version="1.0" encoding="UTF-8"?>
<hudson.model.ListView>
<name>viewName</name>
<filterExecutors>false</filterExecutors>
<filterQueue>false</filterQueue>
<properties class="hudson.model.View$PropertyList"/>
<jobNames>
<comparator class="hudson.util.CaseInsensitiveComparator"/>
</jobNames>
<jobFilters/>
<columns>
<hudson.views.StatusColumn/>
<hudson.views.WeatherColumn/>
<hudson.views.JobColumn/>
<hudson.views.LastSuccessColumn/>
<hudson.views.LastFailureColumn/>
<hudson.views.LastDurationColumn/>
<hudson.views.BuildButtonColumn/>
</columns>
</hudson.model.ListView>
and to check if a view exists:
curl -X POST -H "Content-Type:application/xml" "http://jenkins_host/checkViewName?value=viewName"
to check if a job exists:
curl -X POST -H "Content-Type:application/xml" "http://jenkins_host/checkJobName?value=jobName"
To create a job:
curl -X POST -H "Content-Type:application/xml" -d "<project><builders/><publishers/><buildWrappers/></project>" -u username: API_Token http://JENKINS_HOST/createItem?name=AA_TEST_JOB2
To build a job:
curl -X POST -u username:API_TOKEN http://JENKINS_HOST/job/MY_JOB_NAME/build
In case you need to make the same HTTP calls using the Python requests library, instead of CURL...
Download a job config:
import requests
auth = ("username", "api_token")
url = "http://" + JENKINS_HOST + "/job/" + JOB_NAME + "/config.xml"
response = requests.get(url, auth=auth)
open('config.xml', 'wt').write(response.text)
Create a new job using same config:
url = "http://" + JENKINS_HOST + "/createItem?name=" + NEW_JOB_NAME
headers = {'content-type': 'text/xml'}
data = response.text
response = requests.post(url, auth=auth, headers=headers, data=data)
Omit auth parameter when not needed.